Android设置alarmManager每天触发

时间:2016-11-11 09:19:32

标签: android alarmmanager

在我的应用中,我需要每天下午2:00开始服务。现在我编写了一次触发警报的代码,每次打开应用程序时都会运行此代码:

    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。如果设备处于Doze模式,我将setAndAllowWhileIdle()用于23以上的sdk。我在这个功能中找不到任何可以设置闹钟每天重复的选项。

Q2。我对setInexactRepeating()也有疑问,通常设置参数INTERVAL_DAY每天重复,但在docs中,它说

  

从API 19开始,所有重复警报都将不准确并受制于   无论其规定的重复间隔如何,都要与其他警报进行批处理。

这是否意味着INTERVAL_DAY不再起作用,那么如何在不重新运行此功能的情况下每天设置闹钟并重置alarmManager?

1 个答案:

答案 0 :(得分:1)

尝试以下代码可以解决您的问题 -

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);

  }