entertainment

I Stimuli, your entertainment hub for movies, music and books.

Search The Movie Database and The Open Movie Database for movies and TV shows.

Watch movies on Amazon and Youtube.

Search Spotify for music. Play music on Spotify.

Buy books, music and movies on Amazon.

Managing an Android device's awake state

  • Written by  Clive

Device sleeping on the job? Here’s how you can manage the device awake state

Android wakelocks icon 

You can schedule work to be done. Problem is, nothing will happen if the CPU is sleeping!

The solution is to use a wake lock to prevent the CPU from sleeping while it’s doing your work.

You may also want to keep the screen from turning off. Read on and we’ll show you how…

The Silver Screen: Keeping it on

Some apps, like movie apps or games, need the screen to be on all the time.

You can keep the screen on by including the keepScreenOn attribute in your XML layout. You can also use a flag in your activity like this:

Android FLAG_KEEP_SCREEN_ON

You don’t need any permission. Simply add the flag to keep the screen on

If you want to cancel it just include this bit of code:

Android clearFlags FLAG_KEEP_SCREEN_ON

Clear the flag if you no longer need the screen to stay on

No sleeping on the job: Keep the CPU on

If your app needs to do any work then the CPU has to be running. There’s just one problem, running the CPU drains the battery.

Sometimes you may have to keep the CPU running to do some important work. You can use Android’s Power Manager system Service called a Wake lock to keep the CPU awake while it does your work.

Wake locks

Wake locks keep the CPU running. This drains the battery so use them only when necessary and only for short periods.

You need permission to use a Wake lock:

Android permission WAKE_LOCK

Include this line in your AndroidManifest.xml file

Types of Wake locks

There are a couple of types of Wake locks:

  • FULL_WAKE_LOCK – the screen is on full bright, the keyboard backlight is on, and the CPU is running
  • SCREEN_BRIGHT_WAKE_LOCK – the screen is on full bright, and the CPU is running
  • SCREEN_DIM_WAKE_LOCK – the screen is on, it’s able to be dimmed, and the CPU is running
  • PARTIAL_WAKE_LOCK – the screen and keyboard backlight may be turned off but it keeps the CPU running. This is commonly used for Services started with intent receivers which may receive intents while the device is asleep

How to Use a Wake lock

You can use it directly in your code.

The preferred way is to use a broadcast receiver together with a Service. Typically you’d use a WakefulBroadcastReceiver. The WakefulBroadcastReceiver is designed to manage PARTIAL_WAKE_LOCK’s.

Whichever method you use, it’s important to release the wake lock as soon as your app has finished using it.

Using the WakefulBroadcastReceiver

The WakefulBroadcastReceiver takes care of creating and managing a PARTIAL_WAKELOCK, making sure the device is awake while a Service does the work.

Our Tutorial app

Our tutorial app will show you how you can use a wake lock in your app.

Our app starts with the main activity where we set the screen to stay on.

Pressing a button cancels the “permanent screen on” and starts the second activity.

Pressing a button in the second activity starts an AsyncTask.

We acquire a wake lock in the AsyncTask and do some work in the background. When the work is complete we release the wake lock and send an intent to a WakefulBroadcastReceiver.

The WakefulBroadcastReceiver starts a wakeful service (an IntentService). This is where we do some work, release the wake lock when finished and then start the main activity.

You can follow the steps in the LogCat:

Android permission WAKE_LOCK tutorial LogCat

Follow the steps in the LogCat while the app runs

The MainActivity activity

Launching the app starts the main activity which displays a button.

Keep the screen on

We specify that the screen should be kept on by adding the FLAG_KEEP_SCREEN_ON flag in the activity’s onCreate() method.

Cancel screen on

Pressing the button, clears the flag, allowing the screen to be turned off. It also starts the SecondActivity activity.

The SecondActivity activity

The second activity displays a button. Pressing the button starts an AsyncTask, MyInnerAsyncTask.

We acquire the wake lock in the AsyncTask’s doInBackground() method:

Android acquire wake lock

Get an instance of the PowerManager and acquire a wake lock to keep the CPU running

Note the following:

  • powerManager – an instance of the PowerManager which gives us control over the power state of the device
  • wakeLock – creates a new wake lock. There are two parameters but we’re only interested in the first one:
    • PARTIAL_WAKE_LOCK – ensures that the CPU remains awake but allows the screen and keyboard backlight to be turned off
  • acquire – acquires the wake lock

We simulate some work by “sleeping” for 3 seconds.

The AsyncTask’s onPostExecute’s method is executed when the work is complete:

Android release wake lock onPostExecute

Release the wake lock in the AsyncTask’s onPostExecute’s method

Note the following:

  • release – we release the wake lock
  • intent – we create a broadcast intent. It has two parameters:
    • the context
    • the receiver of the broadcast, MyWakefulReceiver
  • sendBroadcast – we broadcast the intent

The WakefulBroadcastReceiver

Our broadcast receiver, MyWakefulReceiver extends the WakefulBroadcastReceiver class. It manages a partial wake lock for us.

We need to request permission to use the wake lock so we include the following line in the manifest:

Android release wake lock permission WAKE_LOCK

Include the WAKE_LOCK permission attribute in the manifest

Here’s the receiver’s code:

Android release wake lock wakefulReceiver

Our broadcast receiver starts the wakeful Service

Note the following:

  • we extend the WakefulBroadcastReceiver class
  • service – our broadcast intent. It has two parameters:
    • the context
    • the Service that we want to start
  • startWakefulService – acquires a wake lock and starts the Service. It has two parameters:
    • the context
    • the Service that we want to start

Add the Receiver and the Service to your AndroidManifest.xml file:

Android wake lock register service and receiver in manifest

Register the Service and the Broadcast Receiver in the manifest

The IntentService

Our IntentService, MyIntentService is started by the broadcast receiver.

The onHandelIntent() method does some simulated work (sleeping again!) in the worker thread. The wake lock is released when the work is completed when we call:

Android wake lock completeWakefulIntent

Call completeWakefulIntent() to release the wake lock

We then go back to the main activity. Here’s the code to do that:

Android wake lock startActivity

Use an intent to start the main activity

Note the following:

  • goMainIntent – our intent to start the main activity. It has two parameters:
    • the context
    • the activity that we want to start
  • FLAG_ACTIVITY_NEW_TASK – we have to include this flag to be able to start an activity from within a Service. This activity will now become the start of a new task on the stack. If a task is already running for this activity then it will be brought forward and displayed and a new activity will not be started
  • startActivity – starts the MainActivity activity

Wakelocks should only be used when necessary and only for short periods.

Plan B: So what else is there?

There are alternatives to using wake locks:

  • DownloadManager – use it for long running downloads
  • Sync Adapters – use them to synchronise data between your apps and a web server
  • Repeating Alarms – enables you to start operations even when your app is not running

I hope that you have found this tutorial helpful.

You can download the project files here Download icon

Are you using Eclipse or another IDE? Here's how you can use this project's Android Studio files.