Why is it suggested generally to pass a pending intent for an Intent Service when using alarm manager? The same thing can be done in the onreceive() function of the broadcast receiver called by the alarmmanager. What is the advantage with using a service(Intent Service)?
Share
If everything that you need done can be completed in
onReceiveof aBroadcastReceiver, then you should use that, not anIntentService.If you want to do anything after the
BroadcastReceiver, then you should use theIntentService. For example, if you want yourBroadcastReceiverto start aService, and you want the service to gain aWakeLock, then you should be using anIntentServiceinstead.The reason is that
AlarmManageronly guarantees that theonReceiveof aBroadcastReceiverwill be run, even if you useRTC_WAKEUP. So, it is slightly possible that if you use theBroadcastReceiver/Servicecombination, then the CPU will fall asleep before theServicecan acquire theWakeLock– this is, unless you acquire aWakeLockin theBroadcastReceiverand you acquire one in the service, perhaps via astaticWakeLock. But this is… messy, I suppose.Btw, I have never implemented an
IntentService. I just use theBroadcastReceiverandServicecombo and have never had a problem reported. All the information I provided are things I read from other SO posts (primarily from CommonsWare)EDIT:
The 50ms time frame I read from something CommonsWare posted on StackOverflow, and CommonsWare seems to be a rather reliable source of knowledge for Android.
I looked it up and, The docs do say:
And they also say:
BroadcastReceiverwill die because theonReceivewill likely finish running before you get the response back.Though, I suppose the reason for the 50ms time frame is so you don’t risk causing an ANR or any lag. Because if you use a
Service, then you can start a newThread, and it will not block. You would not be able to start a newThreadin aBroadcastReceiverbecause the code after the thread would continue to run, theBroadcastReceiverwould die, and then theThreadwould die, too.