【问题标题】:Prevent alarm from going off when device is asleep防止设备在睡眠时发出警报
【发布时间】:2014-04-04 18:09:26
【问题描述】:

我设置了一个重复闹钟,我只想在设备唤醒时响起。当它睡着时,我希望它停止(并在设备唤醒时重新启动)。但是,无论如何,它目前正在关闭。以下是我注册闹钟的方法:

    Intent updateIntent = new Intent(UPDATE_INTENT);
    AlarmManager alarmService = (AlarmManager) context.getSystemService(
            Context.ALARM_SERVICE);
    PendingIntent updatePendingIntent = PendingIntent.getBroadcast(context, 0,
            updateIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    alarmService.setInexactRepeating(AlarmManager.RTC, Calendar.getInstance().getTimeInMillis(), UPDATE_INTERVAL, updatePendingIntent);

警报管理器文档说 RTC 不会唤醒设备。文档准确地指定了我想要的行为:

Alarm time in System.currentTimeMillis() (wall clock time in UTC). This alarm does not wake the device up; if it goes off while the device is asleep, it will not be delivered until the next time the device wakes up.

当我按下设备上的锁定按钮时,我在 logcat 中清楚地看到来自 PowerManager 的进入睡眠消息:

I/PowerManagerService(488): Going to sleep by user request...

然后我的闹钟还是响了。这里发生了什么?

具有讽刺意味的是,我在 SO 上发现的所有其他问题都涉及设备处于睡眠状态时不会响起的警报。我希望我有他们的问题!

【问题讨论】:

  • UPDATE_INTERVAL的值是多少?
  • 出于测试目的,我将其设置为 10 秒 (10000)。但在生产中需要几个小时。
  • 你试过用 2 到 3 分钟测试它吗?值得尝试排除一些事情。

标签: android


【解决方案1】:

但是,无论如何,它目前正在关闭。

可能有其他东西持有部分WakeLock,并且设备实际上并未处于睡眠状态,即使屏幕可能已关闭。使用 adb shell dumpsys power 尝试追踪它(查找“唤醒锁”部分)。

【讨论】:

  • 这里是唤醒锁部分:唤醒锁:size=0 Suspend Blockers:size=2 PowerManagerService:ref count=0 PowerManagerService.Broadcasts:ref count=0
  • @Adam: 嗯... AFAIK,“ref count=0”表示那些挂起阻止程序没有保持设备唤醒。您可以在其他环境(例如模拟器)上尝试您的代码吗?
【解决方案2】:

我最终决定注册广播接收器来监听 SCREEN_ON 和 SCREEN_OFF,并适当地切换警报。我意识到这可能不是超级优雅,但至少即使另一个应用程序持有唤醒锁,它也始终有效。

监听屏幕开启和关闭:android: broadcast receiver for screen on and screen off

关闭闹钟:How to stop an alarm in android

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多