programmatically set screen to off in android

前端 未结 1 1766
长发绾君心
长发绾君心 2020-12-30 07:21

can I programmatically set screen to off in android if is not done automatically after 1 minute of inactivity.

is this possible to do programmatically in android?

相关标签:
1条回答
  • 2020-12-30 07:51

    Yes, the method best used in this case is to programmatically set screen timeout instead.

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

    1000 is in milliseconds which means 1 second, you can replace it with any value as desired.

    Needed permission:

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

    UPDATE

    It will overwrite the phone system value (Settings/Display/Sleep), so perhaps you need to restore the current settings after finish:

    private static final int SCREEN_OFF_TIME_OUT = 13000;
    private int mSystemScreenOffTimeOut;
    private void setScreenOffTimeOut() {
        try {
            mSystemScreenOffTimeOut = Settings.System.getInt(getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT);
            Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, SCREEN_OFF_TIME_OUT);
        } catch (Exception e) {
            Utils.handleException(e);
        }
    }
    
    private void restoreScreenOffTimeOut() {
        if (mSystemScreenOffTimeOut == 0) return;
        try {
            Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, mSystemScreenOffTimeOut);
        } catch (Exception e) {
            Utils.handleException(e);
        }
    }
    
    0 讨论(0)
提交回复
热议问题