using broadcast recevire with alarm manager in android
-
28-05-2021 - |
Question
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)?
Solution
If everything that you need done can be completed in onReceive
of a BroadcastReceiver
, then you should use that, not an IntentService
.
If you want to do anything after the BroadcastReceiver
, then you should use the IntentService
. For example, if you want your BroadcastReceiver
to start a Service
, and you want the service to gain a WakeLock
, then you should be using an IntentService
instead.
The reason is that AlarmManager
only guarantees that the onReceive
of a BroadcastReceiver
will be run, even if you use RTC_WAKEUP
. So, it is slightly possible that if you use the BroadcastReceiver
/Service
combination, then the CPU will fall asleep before the Service
can acquire the WakeLock
- this is, unless you acquire a WakeLock
in the BroadcastReceiver
and you acquire one in the service, perhaps via a static
WakeLock
. But this is... messy, I suppose.
Btw, I have never implemented an IntentService
. I just use the BroadcastReceiver
and Service
combo 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:
(there is a timeout of 10 seconds that the system allows before considering the receiver to be blocked and a candidate to be killed).
And they also say:
If this BroadcastReceiver was launched through a tag, then the object is no longer alive after returning from this function.
- You should not do anything that takes close to 10 seconds, just to be safe.
- If you do anything that has to wait for a response, the
BroadcastReceiver
will die because theonReceive
will 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 new Thread
, and it will not block. You would not be able to start a new Thread
in a BroadcastReceiver
because the code after the thread would continue to run, the BroadcastReceiver
would die, and then the Thread
would die, too.