androidalarmmanagerandroid-5.0-lollipopandroid-5.1.1-lollipopandroid-powermanager

Create alarm clock on android lollipop


I'm creating an alarm clock. To set the date and time, I use AlarmManager:

AlarmManager am = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);      
PendingIntent pi = PendingIntent.getBroadcast(context, id, intent,  PendingIntent.FLAG_UPDATE_CURRENT);
                    am.set(AlarmManager.RTC_WAKEUP, note.getAlarmTime(), pi);

In my BroadcastReceiver in method onReceive I start new activity (its like dialog with information and playing music) and for unlock screen use:

PowerManager pm;
PowerManager.WakeLock wakeLock;
KeyguardManager.KeyguardLock myLock;

KeyguardManager myKeyGuard = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
    isLocked = myKeyGuard.inKeyguardRestrictedInputMode();

myLock = myKeyGuard.newKeyguardLock(KEYGUARD_SERVICE);

    if (isLocked) {
        myLock.disableKeyguard();
    }

    pm = (PowerManager) getApplicationContext()
            .getSystemService(Context.POWER_SERVICE);
    wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK
            | PowerManager.ACQUIRE_CAUSES_WAKEUP
            | PowerManager.ON_AFTER_RELEASE, "MyWakeLock");
    wakeLock.acquire();

This all works fine, but on Lollipop devices I noticed that the alarm does not always work, especially when the device was blocked for more than 20 minutes. What could it be? Maybe some feature that resets the specified time, or I need a different method to unlock the screen programmatically on android Lollipop?


Solution

  • From Android 19, you should be using the new AlarmManager.setExact() method if you want exact timing instead of AlarmManager.set() as your code does. This is mentioned in the AlarmManager API documentation:

    Note: Beginning with API 19 (KITKAT) alarm delivery is inexact: the OS will shift alarms in order to minimize wakeups and battery use. There are new APIs to support applications which need strict delivery guarantees; see setWindow(int, long, long, PendingIntent) and setExact(int, long, PendingIntent). Applications whose targetSdkVersion is earlier than API 19 will continue to see the previous behavior in which all alarms are delivered exactly when requested.