添加权限。
<uses-permission
android:name="android.permission.WRITE_SETTINGS"
tools:ignore="ProtectedPermissions" />
静态常量。
private static final String SCREEN_OFF_TIMEOUT = "screen_off_timeout";
调用系统设置方法
/**
* 默认无操作后15s屏幕进入休眠
*
* @param isChecked 常亮开关
*/
private void setScreenSaverEnable(boolean isChecked) {
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (!Settings.System.canWrite(this)) {
Intent intent = new Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS,
Uri.parse("package:" + BaseApp.getInstance().getPackageName()));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivityForResult(intent, 1000);
} else {
PrfUtils.setScreenState(isChecked);
if (isChecked) {
Settings.System.putInt(this.getContentResolver(), SCREEN_OFF_TIMEOUT, Integer.MAX_VALUE);//永不休眠
} else {
Settings.System.putInt(this.getContentResolver(), SCREEN_OFF_TIMEOUT, 1000 * 15);
}
}
}
}
注意:
Settings.System.putInt(this.getContentResolver(), SCREEN_OFF_TIMEOUT, 1000 * 15);
value值只会根据系统设定。比如系统设定最小锁屏时间为15s,而代码设置为10s,依旧是15s锁屏