Using Wake Locks

If you leave the tests we wrote so far alone for a few seconds, the screen of your phone will dim. Only if you touch the screen or hit a button will the screen go back to its full brightness. To keep our screen awake at all times, we can use a so-called wake lock.

The first thing we need to do is add a proper <uses-permission> tag in the manifest file with the name android.permission.WAKE_LOCK. This will allow us to actually use the WakeLock class.

We can get a WakeLock instance from the PowerManager like this: PowerManager powerManager =


WakeLock wakeLock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK, "My Lock");

Like all other system services, we acquire the PowerManager from a Context instance. The PowerManager.newWakeLock() method takes two arguments: the type of the lock and a tag we can freely define. There are a couple of different wake lock types; for our purposes the PowerManager.FULL_WAKE_LOCK type is the correct one. It will make sure that the screen will stay on, the CPU will work at full speed, and ] the keyboard will stay enabled.

To enable the wake lock we have to call its acquire() method: wakeLock.acquire();

The phone will be kept awake from this point on, no matter how much time passes without user interaction. When our application is paused or destroyed, we have to disable or release the wake lock again:


Usually we instantiate the WakeLock instance on the Activity.onCreate() method, call WakeLock.acquire() in the Activity.onResume() method, and call the WakeLock.release() method in the Activity.onPause() method. This way we guarantee that our application still performs well in the case of being paused or resumed. Given that there are only four lines of code to add, we're not going to write a full-fledged example. Instead I suggest you simply add it to the full-screen example of the next section and observe the effects.

0 0

Post a comment