Skip to content

Instantly share code, notes, and snippets.

@rajeefmk
Created May 6, 2017 07:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rajeefmk/d4c7318fe9c43c9abe2d14d9793a0978 to your computer and use it in GitHub Desktop.
Save rajeefmk/d4c7318fe9c43c9abe2d14d9793a0978 to your computer and use it in GitHub Desktop.
Code to obtain wake lock.
/**
* Tries to acquire a partial wake lock if not already acquired. Logs errors
* and gives up trying in case the wake lock cannot be acquired.
*/
/**
* Acquire a wake lock if not already acquired.
*
* @param context the context
* @param wakeLock wake lock or null
*/
@SuppressLint("Wakelock")
public static WakeLock acquireWakeLock(Context context,
WakeLock wakeLock) {
Log.i(TAG, "Acquiring wake lock.");
try {
PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
if (powerManager == null) {
Log.e(TAG, "Power manager null.");
return wakeLock;
}
if (wakeLock == null) {
wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
//noinspection ConstantConditions
if (wakeLock == null) {
Log.e(TAG, "Cannot create a new wake lock.");
}
return wakeLock;
}
if (!wakeLock.isHeld()) {
wakeLock.acquire();
if (!wakeLock.isHeld()) {
Log.e(TAG, "Cannot acquire wake lock.");
}
}
} catch (RuntimeException e) {
Log.e(TAG, e.getMessage(), e);
}
return wakeLock;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment