Alarms on the Google Android

痞子三分冷 提交于 2020-01-13 05:35:09

问题


I'm noticing a strange thing with Alarms on Android - they don't always wake up the device at the correct intervals. For example, if I set an alarm to start a service every 5 minutes (using RTC_WAKEUP, or similar), everything works fine until the device goes to sleep - after that, the alarm may not fire for minutes, or close to an hour. It usually does fire eventually - and it always fires if I wake the device by pressing Menu. Using repeating alarms (vs. re-setting them each time) has the same effect.

So my question is, are alarms guaranteed to fire at proper intervals when the device is asleep? I understand that I shouldn't expect millisecond or second precision, but tens of minutes?


回答1:


I've never programmed on Android but I was kinda bored so I googled around and found this, which seems to be very related: http://groups.google.com/group/android-developers/browse_thread/thread/f0303a539de3a74a (you'll need to sign in to your google account in order to read it)

I had another look at the AlarmManager documentation and I noticed that it only talks about using alarms to broadcast events, not start services. I changed things around to use a BroadcastReceiver instead that acquires the lock in its onReceive() and stored the lock reference as a static member of another class, following the example of the AlarmClock application: https://android.googlesource.com/platform/packages/apps/AlarmClock

That seems to have worked. I guess what was happening was that my service starting alarms were being fired, but the device was sometimes going back to sleep before I could acquire the wake lock. Apparently the only guarantee that is made when an alarm is received is that the onReceive will run to completion.

I just thought I'd post this in case anyone is ever searching for the same problem.




回答2:


You should also look at: http://developer.android.com/reference/android/app/AlarmManager.html

Also, when the device is asleep, your program has already had OnPause() called, so only services are running at that point. Meaning that unless your Broadcast Receiver is set to have a wake lock -- the way it suggests in the docs -- the original service call is not going to maintain the device's awake status.



来源:https://stackoverflow.com/questions/1785571/alarms-on-the-google-android

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