Registering from the context

Now we will show you an example of registering a broadcast receiver from the Android Context. To register the receiver you need an instance of it. Let's say that our instance is myReceiver:

    val myReceiver = object : BroadcastReceiver(){ 
         
      ... 
 
     }We need intent filter prepared: 
     val filter = IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)
registerReceiver(myReceiver, filter)

This example will register a receiver that will listen for connectivity information. Since this receiver is registered from the context, it will be valid as long as the context from which we registered is valid. You can also use the LocalBroadcastManager class. LocalBroadcastManager has a purpose to register for and send broadcasts of intents to local objects within your process. This is the example:

    LocalBroadcastManager 
      .getInstance(applicationContext) 
.registerReceiver(myReceiver, intentFilter)

To unregister, perform the following code snippet:

    LocalBroadcastManager 
      .getInstance(applicationContext) 
.unregisterReceiver(myReceiver)

For context subscribed receivers, it's important to pay attention to unregistering. For example, if we register a receiver in the onCreate() method of activity, we must unregister it in the onDestroy() method. If we do not do so, we will have a receiver leaking! Similarly, if we register in onResume() of our activity, we must unregister in onPause(). If we do not do this, we will register multiple times!