Are there any time limits defined for actions run inside a BroadcastReceiver.onReceive method?
Android BroadcastReceiver is a dormant component of android that listens to system-wide broadcast events or intents. When any of these events occur it brings the application into action by either creating a status bar notification or performing a task.
Is it necessary to unregister broadcast receiver? Be mindful of where you register and unregister the receiver, for example, if you register a receiver in onCreate(Bundle) using the activity's context, you should unregister it in onDestroy() to prevent leaking the receiver out of the activity context.
A Broadcast receiver wakes your application up, the inline code works only when your application is running. For example if you want your application to be notified of an incoming call, even if your app is not running, you use a broadcast receiver.
As per the provided link in the teacher's notes, https://developer.android.com/training/monitoring-device-state/connectivity-monitoring.html#MonitorChanges declaring BroadcastReceivers in the manifest is deprecated from Android 7.0 and up.
onReceive()
is called on the main application thread, the same thread that drives your UI. In general, you want onReceive()
to return in under a millisecond, in case your UI is in the foreground, so you do not freeze the UI (a.k.a., have "jank"). There is also a 5-10 second limit, after which Android will basically crash your app.
However, you cannot reliably fork a background thread from onReceive()
, as once onReceive()
returns, your process might be terminated, if you are not in the foreground.
For a manifest-registered receiver, a typical pattern is to have onReceive()
delegate the work to an IntentService
, which has its own background thread and, being a service, tells the OS that your process is still doing some work and should let your process run a bit longer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With