Critical services

If we are running a task and it needs to complete as soon as possible, we can prevent the device's CPU from going to sleep. This allows the task to finish without interruption.

How to do it...

To prevent the CPU from going to sleep, we can use a wake lock:

  1. We will need to ensure that the Xamarin Support Library v4 NuGet or component is installed into the project if we are going to be using the WakefulBroadcastReceiver type.
  2. Before we can prevent the CPU from going to sleep with a wake lock, we need permission to do so:
    [assembly: UsesPermission(Manifest.Permission.WakeLock)]
  3. The recommended way to get hold of a wake lock is to use an instance of WakefulBroadcastReceiver and invoke the StartWakefulService() method:
    [BroadcastReceiver] ...

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.