AlarmManager不工作在休眠模式模式、工作、AlarmManager

2023-09-04 05:41:00 作者:二到无穷大

我设置了​​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的,这意味着该设备可以回去睡觉甚至创建了服务之前。如果你移动到一个广播接收器也应该保持清醒,直到的onReceive完成后的BroadcastReceiver,这意味着你将有时间得到wakelock,开始你的服务。即使你移动到一个的BroadcastReceiver 你将要收购wakelock,直到你完成你的处理,如果它要采取超过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的Andr​​oid的文件第2款:

This is taken from paragraph 2 of the android documentation of AlarmManager:

......如果你的报警接收机名为 Context.startService(),有可能手机会睡的请求的服务推出之前,为prevent这一点,你的BroadcastReceiver和服务将需要实现一个单独的唤醒锁定策略,以确保该手机将继续运行,直到服务变得可用。

"... 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."

 
精彩推荐
图片推荐