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 ...

Get Mastering Android Development with Kotlin now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.