MartinC
MartinC

Reputation: 556

Android Power Manager Wake Lock

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.

Upvotes: 1

Views: 6146

Answers (4)

Ritesh Gune
Ritesh Gune

Reputation: 16729

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();
}

Upvotes: 3

silvia_aut
silvia_aut

Reputation: 1493

Then use this in your oncreate after setContentView:

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

Should help.

Upvotes: 2

TomBoo
TomBoo

Reputation: 391

additional to silvia_aut's answer, try

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

Upvotes: 1

silvia_aut
silvia_aut

Reputation: 1493

try this:

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

and dont forget permissions:

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

Upvotes: 0

Related Questions