Search code examples
androidservicebroadcastreceiverwakelock

Why to put the WakeLock mechanism in BroadcastReceiver instead of having it in the Service?


I am having a look at the sample code from Google team for Android which is WakefulBroadcastReceiver

My question is is there a specific reason to have this mechanism acquire/release in BroadcastReceiver instead of putting this inside the Service itself. If yes what is it ?


Solution

  • It's very useful for something like alarms (see AlarmManager) or other types of PendingIntent use cases. With alarms send to BroadcastReceivers, the alarm manager mechanism ensures that the system will wake long enough to deliver the broadcast Intent (e.g. run the onReceive() method) to BroadcastReceivers only.

    If you were to use a PendingIntent for a Service in this case, the Service would get "started" from an API perspective, but would not necessarily run because the system could go right back to sleep. Using a WakefulBroadcastReceiver, you could instead have the alarm trigger it, take the wake lock and start your Service. The Service would then get an opportunity to run and would ultimately need to release the wake lock so the system could go back to sleep.