Note that there are some explanatory texts on larger screens.

plurals
  1. POCorrect pattern to acquire a WakeLock in a BroadcastReceiver and release it in a Service
    primarykey
    data
    text
    <p>Even after a lot of research I am still not completely sure if the way how I implement a <code>WakeLock</code> for a <code>Service</code> started by a <code>BroadcastReceiver</code> is correct - even though it seems to work fine. The broadcast receiver gets intents sent to it from an alarm, so to start with, from the API docs of <code>AlarmManager</code>:</p> <blockquote> <p>If your alarm receiver called Context.startService(), it is possible that the phone will sleep before the requested service is launched. To prevent this, your BroadcastReceiver and Service will need to implement a separate wake lock policy to ensure that the phone continues running until the service becomes available.</p> </blockquote> <p>So, in <code>onReceive()</code> I do:</p> <pre><code> Intent serviceIntent = new Intent(context, SomeService.class); context.startService(serviceIntent); if(SomeService.wakeLock == null) { PowerManager powerManager = (PowerManager)context.getSystemService(Context.POWER_SERVICE); SomeService.wakeLock = powerManager.newWakeLock( PowerManager.PARTIAL_WAKE_LOCK, SomeService.WAKE_LOCK_TAG); } if(! SomeService.wakeLock.isHeld()) { SomeService.wakeLock.acquire(); } </code></pre> <p>and in the service I do:</p> <pre><code> try { // Do some work } finally { if(wakeLock != null) { if(wakeLock.isHeld()) { wakeLock.release(); } wakeLock = null; } } </code></pre> <p>The <code>SomeService.wakeLock</code>field is package private, static and volatile.</p> <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>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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