Handling network state changes

If we are busy transferring data to or from our device, we need to respond appropriately if the network goes down or if it changes from Wi-Fi to mobile data for some reason.

How to do it...

In order to receive events from the ConnectivityManager instance, we register a BroadcastReceiver instance with the current activity or service:

  1. When we want to access the state of the network, we have to request permission from Android first:
    [assembly: UsesPermission(
      Manifest.Permission.AccessNetworkState)]
  2. After obtaining permission, we create an instance of BroadcastReceiver that will handle network events:
    private class NetworkReceiver : BroadcastReceiver {
      public override void OnReceive(
        Context context, Intent intent) {
      }
    }
  3. In the OnReceive() method, we handle the network events:
    var manager = ConnectivityManager.FromContext(context);
    var networkInfo = manager.ActiveNetworkInfo;
    if (networkInfo != null && networkInfo.IsConnected) {
      // we are connected, so resume a download
    }
    else {
      // no connection, so pause the download
    }
  4. Once we have our receiver, we register it with the activity or service, filtering by the ConnectivityAction action intent:
    var filter = new IntentFilter(
      ConnectivityManager.ConnectivityAction);
    receiver = new NetworkReceiver();
    RegisterReceiver(receiver, filter);
  5. We also have to make sure that we unregister it when we no longer need it:
    if (receiver != null) {
      UnregisterReceiver(receiver);
    }

How it works...

Network connections are unstable and change frequently, especially on a mobile device where the device may have settings changed or physically moved around. The user may move out of range of a hotspot, run out of data, or move from one cell tower to another. Our app needs to handle these changes without impacting the user too much.

In order to handle system events such as network events, we use a BroadcastReceiver instance.

Note

Broadcast receivers are used by Android to send messages across apps.

Implementing a BroadcastReceiver instance is easy, all we have to do is implement the OnReceive() method. This method is invoked when the receiver gets a message from a source, such as from another app or the operating system.

If a broadcast is detected and matches the intent filter, the OnReceive() method is invoked on the broadcast receiver. When a broadcast is received, we can check the network state and then adjust our app accordingly.

The broadcast receiver can be registered with the AndroidManifest.xml file or at runtime. When we register the receiver in the manifest file, the app will receive incoming broadcasts even if it is not running. If we only need to respond when the app is in the foreground; it is better to register the receiver at runtime to reduce system load.

Tip

Broadcast receivers can be registered with the AndroidManifest.xml file or at runtime.

Registering receivers at runtime is done by invoking the RegisterReceiver() method with an IntentFilter instance, and the BroadcastReceiver instance that will respond to the actions in that filter. When the system broadcasts the action, it will not only instantiate our receiver but will also invoke the OnReceive() method.

If we register a receiver at runtime, we need to be sure to unregister it when it is no longer in use. If we register it in the OnResume() method of the activity, we should unregister it in OnPause. We won't receive broadcasts when the app is paused, so unregistering it reduces unnecessary system overhead.

Tip

If a receiver is registered when the activity is resumed, it should be unregistered when the app is paused to reduce system overhead.

There's more...

If our app does not need fine control over how a file is downloaded, we can make use of the DownloadManager instance. This provides a simple interface for managing downloads.

See also

  • The Obtaining a network state recipe
  • The Using DownloadManager recipe
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset