Cemre Mengü
Cemre Mengü

Reputation: 18754

Android wake lock is not released

I get the wake lock like in onCreate method and it works fine (I also set the permissions):

PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Wake lock");
wl.acquire();

However, when I try to release it like:

@Override
protected void onDestroy() 
{
    super.onDestroy();
    wl.release();
}

it is not released for some reason. How is this possible ? Any ideas ?

EDIT: I have an exit button which calls finish() which then calls onDestroy(). When I press the exit button and then put the phone to sleep I expect my program not to work but it works which shows me that the lock is not released

Upvotes: 1

Views: 5700

Answers (3)

Jame
Jame

Reputation: 3854

This is my solution. You can use isHeld() function to do it

 if (wl!= null && wl.isHeld()) {
    wl.release();
    wl= null;
 }

Upvotes: 1

CommonsWare
CommonsWare

Reputation: 1006539

The right way to determine whether your WakeLock-releasing code works is to use adb shell dumpsys power, before and after the release, to see if your WakeLock is released. Since other apps can request and acquire WakeLocks whenever they want, other casual checks (e.g., does my app run when the screen is off?) will be unreliable.

Upvotes: 5

TNR
TNR

Reputation: 5869

Change release() code to onPause() of the Activity. As per Android documentation, it is explained that to call acquire() in onResume() of Activity and release wakelock in onPause() of the Activity. In your case you are making the Activity sleep but not destroying it so it will not release the wakelock. So move it to onPause().

Upvotes: 1

Related Questions