Alarmmanager setup problems delayed the scheduled task

Android 6.0 introduces a new mechanism --Doze power saving mode, the system information screen will broadcast some of the network ah ah what are cut off or reduce the frequency, all we set alarm clock radio also been delayed, after the android6.0 if you want to continue to maintain the Alarm can still be an immediate response when the phone is in the so-called Doze mode, you need to use two methods setAndAllowWhileIdle AlarmManager new offer () or setExactAndAllowWhileIdle ()

Finally, write the code this way:

AlarmManager alarmMgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(action);
    PendingIntent pendIntent = PendingIntent.getBroadcast(getApplicationContext(),requestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.M)
    {       
        alarmMgr.setExactAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP,triggerAtTime,pendIntent);
    }else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
         alarmMgr.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP,triggerAtTime,pendIntent);
    }else{
         alarmMgr.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,triggerAtTime,pendIntent);
    }

If you are going to set the repeating alarm, such as a seven every day to do what tasks, preceded by

manager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 24 * 60 * 60 * 1000, sender);

Should now

manager.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 24 * 60 * 60 * 1000, sender;

But it seems there are still about one minute delay, frustration!

Published 24 original articles · won praise 5 · views 20000 +

Guess you like

Origin blog.csdn.net/qq_26923265/article/details/84023649