本文实例讲述了Android编程调节屏幕亮度(背景灯)及保持背景灯常亮的方法。分享给大家供大家参考,具体如下:
Android写的应用程序其实可以调节屏幕亮度的,查了一下资料发现WindowManager.LayoutParams这个类就包含了调节亮度的参数:
1
2
|
WindowManager.LayoutParams lp = getWindow().getAttributes(); lp.screenBrightness = 0 .1f; |
其中参数screenBrightness就是设置屏幕亮度的0.0f屏幕最暗,1.0f屏幕最亮
在此基础上我又加了一个SeekBar来调节屏幕亮度,
代码参考如下:
此外在回调函数中必须有如下这句话 getWindow().setAttributes(lp); 否则不起作用。我在开始的时候在onCreate()函数中直接设的值,没有这个函数,就能直接调节,但是在回调函数中不加上就不起作用
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
|
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>
下面是控制代码实例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
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程序设计有所帮助。