Listening for network events

The last improvement we want is the ability for our application to execute synchronization when connectivity is established. Create a new class called in the same NetworkReceiver package. Make sure you have the implementation like this:

    class NetworkReceiver : BroadcastReceiver() {
private val tag = "Network receiver"
private var service: MainService? = null

private val serviceConnection = object : ServiceConnection { override fun onServiceDisconnected(p0: ComponentName?) { service = null } override fun onServiceConnected(p0: ComponentName?, binder:
IBinder?) { if (binder is MainService.MainServiceBinder) { service = binder.getService() service?.synchronize() } } } override fun onReceive(context: Context?, p1: Intent?) { context?.let { val cm = context.getSystemService
(Context.CONNECTIVITY_SERVICE) as ConnectivityManager val activeNetwork = cm.activeNetworkInfo val isConnected = activeNetwork != null &&
activeNetwork.isConnectedOrConnecting if (isConnected) { Log.v(tag, "Connectivity [ AVAILABLE ]") if (service == null) { val intent = Intent(context,
MainService::class.java) context.bindService( intent, serviceConnection,
android.content.Context.BIND_AUTO_CREATE ) } else { service?.synchronize() } } else { Log.w(tag, "Connectivity [ UNAVAILABLE ]") context.unbindService(serviceConnection) } } }
}

This receiver will receive messages when a connectivity event occurs. Each time when we have a context and connectivity, we will bind to the service and trigger synchronization. Do not bother with frequent synchronization triggering as, in the next chapters, we will protect ourselves from it in the synchronization method implementation itself. Register your listener by updating the Journaler application class as follows:

     class Journaler : Application() { 
       ... 
       override fun onCreate() { 
          super.onCreate() 
          ctx = applicationContext 
          Log.v(tag, "[ ON CREATE ]") 
          val filter =  
IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION) registerReceiver(networkReceiver, filter) } ... }

Build and run your application. Turn off your connections (Wi-Fi, Mobile) and turn it on again. Observe the following Logcat output:

... V/Network receiver: Connectivity [ AVAILABLE ] 
... V/Network receiver: Connectivity [ AVAILABLE ] 
... V/Network receiver: Connectivity [ AVAILABLE ] 
... W/Network receiver: Connectivity [ UNAVAILABLE ] 
... V/Network receiver: Connectivity [ AVAILABLE ] 
... V/Network receiver: Connectivity [ AVAILABLE ] 
... V/Network receiver: Connectivity [ AVAILABLE ]