Android set alarmManager to trigger daily

*爱你&永不变心* 提交于 2021-01-28 19:11:42

问题


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. 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. 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

As of API 19, all repeating alarms will be inexact and subject to batching with other alarms regardless of their stated repeat interval.

Does this mean INTERVAL_DAY does not work anymore, so how can I set the alarm daily without rerunning this function and reset alarmManager?


回答1:


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

  }


来源:https://stackoverflow.com/questions/40544693/android-set-alarmmanager-to-trigger-daily

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!