目录
目录使用场景屏幕亮度调节模式获取屏幕亮度值设置系统屏幕亮度值设置当前窗口亮度使用场景
最近在研究AndroidL Settings的代码,写了一个简单的控件来操控屏幕亮度。
其实,调节屏幕亮度的场景应用很广,例如很多视频应用都响应touch事件来进行亮度调节。
屏幕亮度调节模式
首先,需要明确屏幕亮度有两种调节模式:
Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC:值为1,自动调节亮度。Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL:值为0,手动模式。
如果需要实现亮度调节,首先需要设置屏幕亮度调节模式为手动模式。
设置方法如下:
public void setScrennManualMode() {ContentResolver contentResolver = getActivity().getContentResolver();try {int mode = 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.SettingNotFoundException e) {e.printStackTrace();}}
获取屏幕亮度值
这里需要了解:
屏幕最大亮度为255。屏幕最低亮度为0。屏幕亮度值范围必须位于:0~255。
设置屏幕亮度的方法:
private int getScreenBrightness() {ContentResolver contentResolver = getActivity().getContentResolver();int defVal = 125;return Settings.System.getInt(contentResolver,Settings.System.SCREEN_BRIGHTNESS, defVal);}
设置系统屏幕亮度值
在设置系统屏幕亮度前,需要保证AndroidManifest.xml中声明如下权限:
<uses-permission android:name="android.permission.WRITE_SETTINGS"/>
当屏幕亮度模式为0即手动调节时,可以通过如下代码设置屏幕亮度:
private void saveScreenBrightness() {setScrennManualMode();ContentResolver contentResolver = getActivity().getContentResolver();int value = 255; // 设置亮度值为255Settings.System.putInt(mContentResolver,Settings.System.SCREEN_BRIGHTNESS, value);}
设置当前窗口亮度
很多视频应用,在touch事件处理屏幕亮度时,并不是修改的系统亮度值,而是修改当前应用所在窗口的亮度。具体做法就是修改LayoutParams中的screenBrightness属性。参考代码如下:
private void setWindowBrightness(int brightness) {Window window = getWindow();WindowManager.LayoutParams lp = window.getAttributes();lp.screenBrightness = brightness / 255.0f;window.setAttributes(lp);}
如果觉得《Android设置屏幕亮度》对你有帮助,请点赞、收藏,并留下你的观点哦!