Will a Handler postDelayed not being fired when CPU sleeps?

♀尐吖头ヾ 提交于 2019-12-03 16:54:13

问题


I have an activity with some Handlers that are being executed at intervals no more than 5 minutes. The activity is launched from a BroadcastReceiver and may be launched with the screen off waiting for the user to grab the phone and get the user input, when this happens, the activity onPause() is called so for sure CPU is in sleep mode. I have not set the activity to turn screen on because I want to save as much battery as possible.

I've tested it with my phone and works really well, while screen is off all Handlers execute all the code they have to run. If I turn the screen on and off while the activity is open everything works fine.

Now, I've read everywhere that some devices does not work as expected when screen goes off and CPU sleeps, most of the times with accelerometers. Now my question is, do I need to acquire a WakeLock so the CPU does not sleep while my activity is open? I really want to know this because, as I said before, I don't want to 'waste' battery by acquiring an expensive WakeLock.

I would prefer a detailed answer of a person that really knows how this works.


回答1:


Your goal cannot be stably achieved by your approach. If you use an Handler's postDelayed() method and the CPU goes to deepsleep, the ms counter will stop and will only continue if the CPU wakes up again.

See this for more detail.

So if you want to have some kind of a cron job you will need to use wakelock. Fortunately there is a Service implementation that does exactly that: Wakeful IntentService

From the doc:

The recommended pattern for Android's equivalent to cron jobs and Windows scheduled tasks is to use AlarmManager. This works well when coupled with an IntentService, as the service will do its work on a background thread and shut down when there is no more work to do. There's one small problem: IntentService does nothing to keep the device awake. If the alarm was a WAKEUP variant, the phone will only stay awake on its own while the BroadcastReceiver handling the alarm is in its onReceive() method. Otherwise, the phone may fall back asleep. WakefulIntentService attempts to combat this by combining the ease of IntentService with a partial WakeLock.



来源:https://stackoverflow.com/questions/17324587/will-a-handler-postdelayed-not-being-fired-when-cpu-sleeps

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!