清华大佬耗费三个月吐血整理的几百G的资源,免费分享!....>>>
这个原理很简单,相信大家都比较熟悉安卓的图形渲染过程,所以就不介绍了,大概原理就是修改window的亮度,然后达到让屏幕变黑的效果,通过监听activity的
dispatchTouchEvent方法来全局监听屏幕的变化。
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); } }; }