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 O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.