AlarmManager 在睡眠模式下不工作 [英] AlarmManager not working in sleep mode
问题描述
我设置了一个带有重复时间的 AlarmManagr.这是我设置它的方法:
I have set an AlarmManagr with a repeat time. Here is my method by which I am setting it:
public void setAlarmManager(Context context, Intent intent) {
PendingIntent pendingIntent;
pendingIntent = PendingIntent.getService(context, 0, intent, 0);
AlarmManager alarmManager =
(AlarmManager)context.getSystemService(context.ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 10);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(),
40000, pendingIntent);
}
这很好用,除非我的设备进入睡眠模式时闹钟停止工作,直到我手动唤醒我的设备.唤醒设备后,AlarmManager 再次开始工作.
This works fine except when my device goes into sleep mode the the alarm stops working until I awake my device manually. After waking the device the AlarmManager start working again.
如何让管理器即使在睡眠模式下也能运行?
How to keep the manager running even in sleep mode?
推荐答案
这是因为你的 PendingIntent
正在调用一个服务而不是一个 BroadcastReceiver
,这意味着设备甚至可以在您的服务创建之前重新进入睡眠状态.如果您移动到广播接收器,它应该"保持唤醒状态,直到 BroadcastReceiver 的 onReceive 完成,这意味着您将有时间获得唤醒锁并启动您的服务.即使您转移到 BroadcastReceiver
,如果处理时间超过 10 秒(这是 BroadcastReceiver
>).
It is because your PendingIntent
is calling to a service and not to a BroadcastReceiver
which means the device can go back to sleep before your service is even created. If you move to a broadcast receiver it "should" stay awake until the onReceive is complete of the BroadcastReceiver which means you will have time to get a wakelock and start your service. Even if you move to a BroadcastReceiver
you will want to acquire a wakelock until you have completed your processing if it's going to take more than 10 seconds (which is the limit of a BroadcastReceiver
).
这是取自 AlarmManager 的 android 文档的第 2 段:
This is taken from paragraph 2 of the android documentation of AlarmManager:
"... 如果您的警报接收器调用了 Context.startService()
,则手机可能会在请求的服务启动之前休眠.为了防止这种情况,您的 BroadcastReceiver 和 Service 将需要实施单独的唤醒锁定策略,以确保手机继续运行,直到服务可用."
"... If your alarm receiver called Context.startService()
, it is possible that the phone will sleep before the requested service is launched. To prevent this, your BroadcastReceiver and Service will need to implement a separate wake lock policy to ensure that the phone continues running until the service becomes available."
这篇关于AlarmManager 在睡眠模式下不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!