Android Power Manager Wake Lock

5.9k Views Asked by At

I've got application which is playing TV streams and needs to be ON all the time. I do acquire wake lock in OnCreate()

pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
wl = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, TAG);
wl.acquire();

and then release in onDestroy()

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

User usually minimize the app by pressing back, home or power button and then resumes from home screen tapping the app icon. I do release wake lock in onPause() and acquire in onResume().

Time to time I see application crashes or disappears completely from screen and I see logs related to wake lock.

Is this a best practice to control Android Power Manager Wake Lock?

Any opinions are welcome.

4

There are 4 best solutions below

1
On

try this:

wl = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "My Tag");

and dont forget permissions:

<uses-permission android:name="android.permission.WAKE_LOCK" />
2
On

additional to silvia_aut's answer, try

if (wakelock.isHeld())
       wakelock.release();
2
On

Then use this in your oncreate after setContentView:

getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

Should help.

0
On

As you are saying that you do release wake lock in onPause() and acquire in onResume(). That is a good practice however alongwith these I suggest you to release wakelock in onUserLeaveHint() as well.

onUserLeaveHint()

@Override
protected void onUserLeaveHint() {

try {
     // your code.

     // release the wake lock
     wl.release();

    }catch(Exception ex){
     Log.e("Exception in onUserLeaveHint", ex.getMessage);
    }
    super.onUserLeaveHint();
}