Android实现长时间不用屏幕变暗

直接上代码,代码如下:

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实现长时间不用屏幕变暗)