Today’s #AndroidDev #Protip from +Katie McCormick is about using WakefulBroadcastReceiver.

A WakefulBroadcastReceiver [1] is a special type of broadcast receiver that takes care of creating and managing a PARTIAL_WAKE_LOCK [2] for your app. A WakefulBroadcastReceiver passes off the work to a Service (typically an IntentService [3]), while ensuring that the device does not go back to sleep in the transition. If you don't hold a wake lock while transitioning the work to a service, you are effectively allowing the device to go back to sleep before the work completes. The net result is that the app might not finish doing the work until some arbitrary point in the future, which is not what you want.

The first step in using a WakefulBroadcastReceiver is to add it to your manifest, as with any other broadcast receiver:

<receiver android:name=".MyWakefulReceiver"></receiver>

The following code starts MyIntentService with the method startWakefulService(). This method is comparable to startService(), except that the WakefulBroadcastReceiver is holding a wake lock when the service starts. The intent that is passed with startWakefulService() holds an extra identifying the wake lock:

public class MyWakefulReceiver extends WakefulBroadcastReceiver {
    public void onReceive(Context context, Intent intent) {
        // Start the service, keeping the device awake while the service is
        // launching. This is the Intent to deliver to the service.
        Intent service = new Intent(context, MyIntentService.class);
        startWakefulService(context, service);
    }
}

When the service is finished, it calls completeWakefulIntent() to release the wake lock. The completeWakefulIntent() method has as its parameter the same intent that was passed in from the WakefulBroadcastReceiver:

public class MyIntentService extends IntentService {
    ...
    protected void onHandleIntent(Intent intent) {
        // Do the work that requires your app to keep the CPU running.
        // ...
        // Release the wake lock provided by the WakefulBroadcastReceiver.
        MyWakefulReceiver.completeWakefulIntent(intent);
    }
}

For more discussion of this topic and a complete sample, see Managing Device Awake State [4].

[1] WakefulBroadcastReceiver http://goo.gl/Zpobfv
[2] PARTIAL_WAKE_LOCK http://goo.gl/iUfJnF
[3] IntentService http://goo.gl/Qx4VHL
[4] Managing Device Awake State http://goo.gl/QPufnL
Shared publiclyView activity