Android编程设置屏幕亮度的方法
本文实例讲述了Android编程设置屏幕亮度的方法。分享给大家供大家参考,具体如下:
使用场景
最近在研究AndroidLSettings的代码,写了一个简单的控件来操控屏幕亮度。
其实,调节屏幕亮度的场景应用很广,例如很多视频应用都响应touch事件来进行亮度调节。
屏幕亮度调节模式
首先,需要明确屏幕亮度有两种调节模式:
Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC:值为1,自动调节亮度。
Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL:值为0,手动模式。
如果需要实现亮度调节,首先需要设置屏幕亮度调节模式为手动模式。
设置方法如下:
publicvoidsetScrennManualMode(){
ContentResolvercontentResolver=getActivity().getContentResolver();
try{
intmode=Settings.System.getInt(contentResolver,
Settings.System.SCREEN_BRIGHTNESS_MODE);
if(mode==Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC){
Settings.System.putInt(contentResolver,Settings.System.SCREEN_BRIGHTNESS_MODE,
Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
}
}catch(Settings.SettingNotFoundExceptione){
e.printStackTrace();
}
}
获取屏幕亮度值
这里需要了解:
1.屏幕最大亮度为255。
2.屏幕最低亮度为0。
3.屏幕亮度值范围必须位于:0~255。
设置屏幕亮度的方法:
privateintgetScreenBrightness(){
ContentResolvercontentResolver=getActivity().getContentResolver();
intdefVal=125;
returnSettings.System.getInt(contentResolver,
Settings.System.SCREEN_BRIGHTNESS,defVal);
}
设置系统屏幕亮度值
在设置系统屏幕亮度前,需要保证AndroidManifest.xml中声明如下权限:
当屏幕亮度模式为0即手动调节时,可以通过如下代码设置屏幕亮度:
privatevoidsaveScreenBrightness(){
setScrennManualMode();
ContentResolvercontentResolver=getActivity().getContentResolver();
intvalue=255;//设置亮度值为255
Settings.System.putInt(mContentResolver,
Settings.System.SCREEN_BRIGHTNESS,value);
}
设置当前窗口亮度
很多视频应用,在touch事件处理屏幕亮度时,并不是修改的系统亮度值,而是修改当前应用所在窗口的亮度。具体做法就是修改LayoutParams中的screenBrightness属性。参考代码如下:
privatevoidsetWindowBrightness(intbrightness){
Windowwindow=getWindow();
WindowManager.LayoutParamslp=window.getAttributes();
lp.screenBrightness=brightness/255.0f;
window.setAttributes(lp);
}
希望本文所述对大家Android程序设计有所帮助。