Search code examples
androidwakelock

Is there a way to lock Android screen after a certain period of time?


My app uses a WakeLock and it automatically turns the screen on when it receives a SMS. I've set the duration so that it releases the WakeLock almost instantaneously, but it seems that in Settings, the minimum time the screen will turn off after inactivity is 15 seconds. I'm looking for the screen to turn off in a shorter period of time - say 5 seconds - to save battery.

I've looked around everywhere and it seems that some people mention something about DevicePolicyManager. I've tried to include the permission in the manifest but it says that it can only be used by a system application. Does this mean it has to be rooted? Is there another workaround?

Here's my code:

public static void wakeScreen(Context context) {
    PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);

    boolean isScreenOn = false;
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT_WATCH) {
        isScreenOn = pm.isInteractive();
    }

    else {
        isScreenOn = pm.isScreenOn();
    }

    if (isScreenOn == false) {
        PowerManager.WakeLock w1 = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK
                |PowerManager.ACQUIRE_CAUSES_WAKEUP
                ,"MyLock");

        w1.acquire(100); //releases the lock almost instantaneously, but still limited by screen timeout in Android settings

    }
}

Solution

  • Never mind, found an easy solution. Just set the timeout manually.

    Settings.System.putInt(context.getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, 1000)