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:

  1. As subscribing to the boot events is a privileged action, we have to request special permission to do so:
    [assembly: UsesPermission(
      Manifest.Permission.ReceiveBootCompleted)]
  2. 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
      }
    }
  3. Once we have ...

Get Xamarin Mobile Development for Android Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.