Created
May 6, 2017 07:53
-
-
Save rajeefmk/d4c7318fe9c43c9abe2d14d9793a0978 to your computer and use it in GitHub Desktop.
Code to obtain wake lock.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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