8

In the https://github.com/commonsguy/cwac-wakeful demo, the OnAlarmReceiver (a BroadcastReceiver) onReceive() method is called in response to an Alarm. The onReceive() method starts the Service. There are two Intents used, one received by the BroadcastReceiver and one by the Service. This seems more complicated that it needs to be, why not just have the Service receive the Intent from the AlamManager?

I understand that the Phone is guaranteed not to sleep while onReceive() is executing i.e. it wrapped with a wake lock. I'm not sure if the Service class offers any similar guarantees.

Is the any way to start the Service directly from an Alarm while still guaranteeing that the Phone will be woken from sleep and won't sleep until a wake lock can be acquired?

alexbirkett
  • 2,604
  • 2
  • 26
  • 30

1 Answers1

14

This seems more complicated that it needs to be, why not just have the Service receive the Intent from the AlamManager?

Because Android will not guarantee that the device will stay awake long enough for a getService() PendingIntent to be invoked. The guarantee is only for a getBroadcast() PendingIntent -- Android ensures that the device will stay awake (via a WakeLock) for the duration of your onReceive() call.

Trust me, I wish we could skip it.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • oh that's great - I was wondering about the same thing - apparently [in the simple alarm example from the API samples this is not a concern](http://stackoverflow.com/a/14094314/281545) - or am I missing something ? – Mr_and_Mrs_D Mar 18 '13 at 17:54
  • 1
    @Mr_and_Mrs_D: That sample has so many issues, it is not even funny. Someday, I'll file an issue to hopefully get it changed. – CommonsWare Mar 18 '13 at 18:07
  • Please do (mention the [comments](http://stackoverflow.com/q/9146647/281545) also) - in my short acquaintance with Android I have already seen more clumsy, buggy, inelegant, confusing code as ever before. What a mess ! – Mr_and_Mrs_D Mar 18 '13 at 18:16
  • Where is this documented? Could you @CommonsWare point me to the source? – Vito Valov Jun 13 '18 at 15:30
  • @VitoValov: "Where is this documented?" -- it's not, outside of some old `android-developers` Google Group posts from Dianne Hackborn and related materials. – CommonsWare Jun 13 '18 at 22:30