在 android 棒棒糖上创建闹钟

Create alarm clock on android lollipop

我正在制作闹钟。要设置日期和时间,我使用 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);

在我的 BroadcastReceiver 方法 onReceive 中,我开始新的 activity(它就像带有信息和播放音乐的对话框)和解锁屏幕使用:

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

一切正常,但我注意到在 Lollipop 设备上警报并不总是有效,尤其是当设备被阻止超过 20 分钟时。会是什么呢?也许某些功能会重置指定时间,或者我需要一种不同的方法来以编程方式在 android Lollipop?

上解锁屏幕

从 Android 19 开始,如果您想要精确计时而不是像您的代码那样使用 AlarmManager.set(),您应该使用新的 AlarmManager.setExact() 方法。 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.