Friday, 15 June 2018

Android handler stop working after screen locked



http://dzy-123.iteye.com/blog/1940285
https://developer.android.com/reference/android/os/PowerManager.WakeLock
https://developer.android.com/training/scheduling/wakelock


Android Timer and handler will stop working after screen locked. if you have things running periodically, it will stop working. (back to work after screen unlocked --- screen light up exactly )


couple of solutions:

Solution 1:
if you don't want to change your logic because you may have logic in handler which change ui in the same activity, then use WakeLock

Call below function before you start your program

PowerManager.WakeLock wakeLock = null;
private void acquireWakeLock() {
    if (null == wakeLock)
    {
        PowerManager pm = (PowerManager)this.getSystemService(Context.POWER_SERVICE);
        wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK|PowerManager.ON_AFTER_RELEASE, "PeriodicallyRefreshOrderData");        if (null != wakeLock)
        {
            wakeLock.acquire();
        }
    }
}

You need to add below permission:

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

Solution 2
or "keepScreenOn" in the activity, which will keep the screen on, but if user manually lock the screen it will not help.

Solution 3:

use service, which i will not introduce details. with this solution you may need to change a lot of your code.


No comments:

Post a comment