Android_调节屏幕亮度(背景灯)及保持背景灯常亮的方法

Android写的应用程序其实可以调节屏幕亮度的,查了一下资料发现WindowManager.LayoutParams这个类就包含了调节亮度的参数:

WindowManager.LayoutParams lp = getWindow().getAttributes();

lp.screenBrightness = 0.1f;

其中参数screenBrightness就是设置屏幕亮度的0.0f屏幕最暗,1.0f屏幕最亮

在此基础上我又加了一个SeekBar来调节屏幕亮度,

代码参考如下:

此外在回调函数中必须有如下这句话 getWindow().setAttributes(lp); 否则不起作用。我在开始的时候在onCreate()函数中直接设的值,没有这个函数,就能直接调节,但是在回调函数中不加上就不起作用

public class BLightActivity extends Activity {
    /** Called when the activity is first created. */
int Max_Brightness = 100;
SeekBar bSeekBar = null;
float fBrightness = 0.0f;
WindowManager.LayoutParams lp = null;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        bSeekBar = (SeekBar) findViewById(R.id.bLightBar);
        bSeekBar.setOnSeekBarChangeListener(seekListener);
        bSeekBar.setMax(Max_Brightness);
        
        lp = getWindow().getAttributes();
//        lp.screenBrightness = 0.1f;
    }
    
    OnSeekBarChangeListener seekListener = new OnSeekBarChangeListener() {
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
fBrightness = (float)progress / (float)Max_Brightness;
lp.screenBrightness = fBrightness;
// 这句得加上,否则屏幕亮度不启作用
getWindow().setAttributes(lp);
System.out.println("FY_" + fBrightness);
}
};
}


下面是介绍保持背景灯常量的方法:

首先是要获得权限 :    

<uses-permission android:name="android.permission.WAKE_LOCK"></uses-permission>

下面是控制代码实例

public class test extends Activity{     
	PowerManager powerManager = null;
    WakeLock wakeLock = null;
    @Override
	protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         this.setContentView(R.layout.main);
         
         this.powerManager = (PowerManager)this.getSystemService(Context.POWER_SERVICE);
         this.wakeLock = this.powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK, "My Lock");
		 this.wakeLock.acquire();
     }
    @Override
    protected void onResume() {
         super.onResume();
		 // 重新获取
         this.wakeLock.acquire();
     }
     @Override
     protected void onPause() {
         super.onPause();
		 // 在Activity销毁的时候释放wakeLock
         this.wakeLock.release();
     }
 }

你可能感兴趣的:(Android_调节屏幕亮度(背景灯)及保持背景灯常亮的方法)