标签:
dispatchTouchEvent方法来全局监听屏幕的变化。
package com.example.test; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.view.MotionEvent; import android.view.WindowManager; public class BaseActivity extends Activity { /** * 最大的屏幕亮度 */ float maxLight; /** * 当前的亮度 */ float currentLight; /** * 用来控制屏幕亮度 */ Handler handler; /** * 延时时间 */ long DenyTime = 5 * 1000L; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); InitData(); } private void InitData() { handler = new Handler(Looper.getMainLooper()); maxLight = GetLightness(this); } /** * 设置亮度 * * @param context * @param light */ void SetLight(Activity context, int light) { currentLight = light; WindowManager.LayoutParams localLayoutParams = context.getWindow().getAttributes(); localLayoutParams.screenBrightness = (light / 255.0F); context.getWindow().setAttributes(localLayoutParams); } /** * 获取亮度 * * @param context * @return */ float GetLightness(Activity context) { WindowManager.LayoutParams localLayoutParams = context.getWindow().getAttributes(); float light = localLayoutParams.screenBrightness; return light; } @Override protected void onPause() { super.onPause(); stopSleepTask(); } @Override protected void onResume() { super.onResume(); startSleepTask(); } @Override public boolean dispatchTouchEvent(MotionEvent ev) { if (currentLight == 1) { startSleepTask(); } return super.dispatchTouchEvent(ev); } /** * 开启休眠任务 */ void startSleepTask() { SetLight(this, (int) maxLight); handler.removeCallbacks(sleepWindowTask); handler.postDelayed(sleepWindowTask, DenyTime); } /** * 结束休眠任务 */ void stopSleepTask() { handler.removeCallbacks(sleepWindowTask); } /** * 休眠任务 */ Runnable sleepWindowTask = new Runnable() { @Override public void run() { SetLight(BaseActivity.this, 1); } }; }
【Android】实现类似于百度长时间不用APP屏幕变暗——不用修改系统设置权限
标签:
原文地址:http://blog.csdn.net/windowsxp2014/article/details/45917193