Java – Android Power Manager Wake Lock

androidandroid-wake-lockjavapower-managementwakelock

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.

Best Answer

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