Durable WakeLock

Context

Implementation,UI

Affects

Energy Efficiency

Problem

A WakeLock is needed to tell the system that the app needs to stay the device on, (to use CPU, Sensors, GPS, Network, etc.). After using the ressources the application should release the WakeLock. If this is not done this will drain the battery.

A WakeLock is aquired by:

PowerManager pm = (PowerManager)mContext.getSystemService(Context.POWER_SERVICE);

PowerManager.WakeLock wl = pm.newWakeLock(
  PowerManager.SCREEN_DIM_WAKE_LOCK
  | PowerManager.ON_AFTER_RELEASE,
  TAG);

wl.acquire();
// ... do work...
wl.release();

Refactorings

Aquire WakeLock with timeout

Resolves

Energy Efficiency

Affects

Solution

To ensure that the WakeLock will be released in all circumstances one can use the method PowerManager.WakeLock.aquire(long timeout).

PowerManager pm = (PowerManager)mContext.getSystemService(Context.POWER_SERVICE);

PowerManager.WakeLock wl = pm.newWakeLock(
  PowerManager.SCREEN_DIM_WAKE_LOCK
  | PowerManager.ON_AFTER_RELEASE,
  TAG);

wl.acquire(60*1000*10); // auto release it in 10 minutes
// ... do work...
wl.release();

Links

Related