Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
660 views
in Technique[技术] by (71.8m points)

android - AlarmManager not working in sleep mode

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...