O'Reilly logo

Xamarin Mobile Development for Android Cookbook by Matthew Leibowitz

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Using BroadcastReceivers

There may be several instances when we would want to listen for the occurrence of events as they occur on the running Android system.

How to do it...

To listen for broadcast system events, we make use of a BroadcastReceiver instance:

  1. To listen for events, we need an instance of BroadcastReceiver:
    public class WorkReceiver : BroadcastReceiver {
      public override void OnReceive(
      Context context, Intent intent) {
      }
    }
  2. Often, broadcast receivers don't do much except starting a service, which does the work on a background thread:
    var service = new Intent(context, typeof(WorkService));
    context.StartService(service);

Once we have a broadcast receiver, we need to register it with the Android system. There are three ways to do this:

  • We can ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required