How can I programmatically turn off screen in android?

moisesvs picture moisesvs · Sep 16, 2016 · Viewed 9.8k times · Source

I want to turn off the screen when the user clicks a button. I am trying to do it with PowerManager class but I don't obtain good results. What is the best way to turn off the screen in android?.

I am using the code below:

    PowerManager pm = (PowerManager)this.getSystemService(
            Context.POWER_SERVICE);
    PowerManager.WakeLock wl = pm.newWakeLock(
            PowerManager.PARTIAL_WAKE_LOCK,
            "");
    wl.acquire();

But only work this code:

    WindowManager.LayoutParams params = getWindow().getAttributes();
    params.flags = WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
    params.screenBrightness = 0;
    getWindow().setAttributes(params);

But, this code only set brightness to 0 but no turns off the screen.

Thanks a lot.

Answer

Mukesh Mande picture Mukesh Mande · Jul 12, 2017

You can turn off screen by overriding system screen turn off time.

First get system turn off time

int defaultTurnOffTime =  Settings.System.getInt(getContentResolver(),Settings.System.SCREEN_OFF_TIMEOUT, 60000);

then put your turn off time

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

and when the screen turned off, set default turn off time

Settings.System.putInt(getContentResolver(),Settings.System.SCREEN_OFF_TIMEOUT, defaultTurnOffTime);

add below permission

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