Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<blockquote> <p>What I am unsure about is the check using <code>isHeld()</code> - does it really tell me if a <code>WakeLock</code> is acquired or not, and do I need to do this check at all?</p> </blockquote> <p>Actually slightly tricky to answer. Looking at the source for <code>PowerManager</code> and <code>PowerManager.WakeLock</code> <a href="https://android.googlesource.com/platform/frameworks/base/+/refs/heads/master/core/java/android/os/PowerManager.java" rel="nofollow">here</a> the <code>WakeLock.acquire()</code> and <code>WakeLock.acquireLocked()</code> methods are as follows...</p> <pre><code>public void acquire(long timeout) { synchronized (mToken) { acquireLocked(); mHandler.postDelayed(mReleaser, timeout); } } private void acquireLocked() { if (!mRefCounted || mCount++ == 0) { // Do this even if the wake lock is already thought to be held (mHeld == true) // because non-reference counted wake locks are not always properly released. // For example, the keyguard's wake lock might be forcibly released by the // power manager without the keyguard knowing. A subsequent call to acquire // should immediately acquire the wake lock once again despite never having // been explicitly released by the keyguard. mHandler.removeCallbacks(mReleaser); try { mService.acquireWakeLock(mToken, mFlags, mTag, mWorkSource); } catch (RemoteException e) { } mHeld = true; } } </code></pre> <p>...<code>mService</code> is an <code>IPowerManager</code> interface and the source for it isn't available so it's hard to tell what may or may not go wrong when attempting to call <code>acquireWakeLock(...)</code>.</p> <p>In any case, the only exception that can be caught is <code>RemoteException</code> and the <code>catch</code> block does nothing. Immediately after the try/catch, <code>mHeld</code> is set <code>true</code> regardless.</p> <p>In short, if you call <code>isHeld()</code> immediately after <code>acquire()</code> the result will always be <code>true</code>.</p> <p>Looking further into the source for <code>PowerManager.WakeLock</code> shows similar behaviour for <code>release()</code> which calls <code>release(int flags)</code> where the <code>mHeld</code> member is always set to <code>false</code> regardless of what happens.</p> <p>In conclusion I'd suggest it is always a good idea to check <code>isHeld()</code> just as a best practice in case later versions of Android change this behaviour of the <code>WakeLock</code> methods.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload