I'd like to know what is the best practice/way of programmatically register a broadcast receiver. I want to register specific receivers according to user choice.
As the registration is done through the manifest file, I'm wondering if there's a proper way to achieve this in code.
In your
onCreate
method you can register a receiver like this:Remember to run this in the
onDestroy
method:One important point that people forget to mention is the life time of the
Broadcast Receiver
. The difference of programmatically registering it from registering in AndroidManifest.xml is that. In the manifest file, it doesn't depend on application life time. While when programmatically registering it it does depend on the application life time. This means that if you register in AndroidManifest.xml, you can catch the broadcasted intents even when your application is not running.Edit: The mentioned note is no longer true as of Android 3.1, the Android system excludes all receiver from receiving intents by default if the corresponding application has never been started by the user or if the user explicitly stopped the application via the Android menu (in Manage → Application). https://developer.android.com/about/versions/android-3.1.html
This is an additional security feature as the user can be sure that only the applications he started will receive broadcast intents.
So it can be understood as receivers programmatically registered in Application's
onCreate()
would have same effect with ones declared in AndroidManifest.xml from Android 3.1 above.Create a broadcast receiver
[BroadcastReceiver(Enabled = true, Exported = false)]
From your activity add this code:
Define a broadcast receiver anywhere in Activity/Fragment like this:
Define IntentFilter in onCreate()
Now register the BroadcastReciever in onResume() and Unregister it in onPause [because there is no use of broadcast if activity is paused].
For detail tutorial, have a look at broadcast receiver-two ways to implement.
for LocalBroadcastManager
and register in
onResume
and Unregister it
onStop
and recieve it ..
where IntentFilter is