Android画面は常にN秒後に自動的に暗い画面が点灯します
1861 ワード
Androidは、ユーザーが操作しない場合は、タイミングを決めて画面を暗くして、体験ができます.コードを直接見ましょう.
//
private float maxLight;
//
private float currentLight;
//
private Handler lightHandler;
// 60 ,
private long delayTime = 60 * 1000L;
protected void onCreate() {
//
getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
//
lightHandler = new Handler(Looper.getMainLooper());
maxLight = getLightness();
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
if (currentLight == 1) {
startSleepTask();
return false;
}
startSleepTask();
return super.dispatchTouchEvent(ev);
}
/**
*
*/
private float getLightness() {
WindowManager.LayoutParams localLayoutParams = this.getWindow().getAttributes();
return localLayoutParams.screenBrightness;
}
/**
*
*/
private void setLightness(int light) {
currentLight = light;
WindowManager.LayoutParams localLayoutParams = this.getWindow().getAttributes();
localLayoutParams.screenBrightness = (light / 255.0F);
this.getWindow().setAttributes(localLayoutParams);
}
/**
*
*/
private void startSleepTask() {
setLightness((int) maxLight);
stopSleepTask();
lightHandler.postDelayed(sleepWindowTask, delayTime);
}
/**
*
*/
private void stopSleepTask() {
lightHandler.removeCallbacks(sleepWindowTask);
}
/**
*
*/
Runnable sleepWindowTask = new Runnable() {
@Override
public void run() {
setLightness(1);
}
};