1. 程式人生 > >Android實現長時間不用螢幕變暗

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);  
        }  
    };  
   
}