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:
To listen for events, we need an instance of
BroadcastReceiver
:public class WorkReceiver : BroadcastReceiver { public override void OnReceive( Context context, Intent intent) { } }
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 automatically register the receiver when the app is installed using the
[BroadcastReceiver]
attribute:[BroadcastReceiver] [IntentFilter(new []{ "xamarincookbook.Work" })]
We can also manually register the receiver using the
RegisterReceiver(...