Android设置alarmManager每天触发 [英] Android set alarmManager to trigger daily
问题描述
在我的应用中,我需要在每天下午 2:00 启动一项服务.现在我写了一次触发警报的代码,每次打开应用程序都会运行这段代码:
In my app, I need to start a service at 2:00pm daily. Right now I wrote the code to trigger the alarm once, this code is ran every time I open the app:
AlarmManager alarmMgr = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, DownloadReceiver.class);
PendingIntent pIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmMgr.cancel(pIntent);
Calendar cal= Calendar.getInstance();
cal.setTimeInMillis(System.currentTimeMillis());
cal.set(Calendar.HOUR_OF_DAY,refreshhour);
cal.set(Calendar.MINUTE,refreshmin);
cal.set(Calendar.SECOND, 0);
// if the scheduler date is passed, move scheduler time to tomorrow
if (System.currentTimeMillis() > cal.getTimeInMillis()) {
cal.add(Calendar.DAY_OF_YEAR, 1);
}
if(android.os.Build.VERSION.SDK_INT>=23) {
alarmMgr.setAndAllowWhileIdle(AlarmManager.RTC_WAKEUP,
cal.getTimeInMillis(), pIntent);
}
else{
alarmMgr.setInexactRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, pIntent);
}
Q1. 我使用 setAndAllowWhileIdle()
来处理 23 以上的 sdk,以防设备在 打盹 模式.我在此功能中找不到任何可以将闹钟设置为每天重复的选项.
Q1. I used setAndAllowWhileIdle()
for sdk above 23 in case the device is in Doze mode. I cannot find any option in this function that I can set the alarm to repeat every day.
Q2. 我也有关于 setInexactRepeating()
的问题,通常通过设置参数 INTERVAL_DAY
将它设置为每天重复,但是在 文档,上面写着
Q2. I also have questions about setInexactRepeating()
, normally it is set to repeat every day by setting the parameter INTERVAL_DAY
, but in the docs, it says
从 API 19 开始,所有重复的警报都将不准确并受制于与其他警报一起批处理,而不管它们规定的重复间隔如何.
As of API 19, all repeating alarms will be inexact and subject to batching with other alarms regardless of their stated repeat interval.
这是否意味着 INTERVAL_DAY
不再起作用,那么如何在不重新运行此功能并重置 alarmManager 的情况下每天设置闹钟?
Does this mean INTERVAL_DAY
does not work anymore, so how can I set the alarm daily without rerunning this function and reset alarmManager?
推荐答案
试试下面的代码就能解决你的问题-
Try below code will solve your problem-
AlarmManager alarmMgr = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
boolean flag = (PendingIntent.getBroadcast(this, 0,
new Intent("totime.action.string"),
PendingIntent.FLAG_NO_CREATE) != null);
if(!flag)
{
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 14);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
Intent intent = new Intent("totime.action.string");
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) Data_Graph.this.getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),(24*60*60*1000), pendingIntent);
}
这篇关于Android设置alarmManager每天触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!