Starting services automatically
We might have a long-running task that we need to execute when the device starts. This may be needed to set up some service or configuration for other services.
How to do it...
When we want to perform a task when the device starts up, we can start a service when we receive the ActionBootComplete
intent action:
As subscribing to the boot events is a privileged action, we have to request special permission to do so:
[assembly: UsesPermission( Manifest.Permission.ReceiveBootCompleted)]
Before we can start our task, we need a
Service
instance that will perform the actual task:[Service] public class XamarinService : IntentService { protected override void OnHandleIntent(Intent intent) { // some startup task } }
Once we have the service and permission, we need to listen for the boot events using a
BroadcastReceiver
instance:[BroadcastReceiver] [IntentFilter(new []{ Intent.ActionBootCompleted })] public class ServiceStarter : BroadcastReceiver { public override...