最近有一个调整屏幕亮度的需求,在网上找了各种代码,心乱如麻。不是长篇大论说源码的,就是只言片语就上代码的,关键是代码还不能直接用。
这里面确实是有一些坑,在这里我会把可以用的代码写出来,并且告诉大家坑在哪里。希望可以帮到大家。
经过我的初步分析,屏幕的亮度分为两种情况:
1、全局屏幕亮度,作用于整个手机环境。
2、当前屏幕亮度,仅作用于当前的activity。
我先上第一种情况的代码
-
-
-
-
- public class ScreenManager {
-
-
-
-
-
-
- public static int getScreenMode() {
- int mode = -1;
- try {
- mode = Settings.System.getInt(APP.context.getContentResolver(),
- Settings.System.SCREEN_BRIGHTNESS_MODE);
- } catch (Settings.SettingNotFoundException e) {
- e.printStackTrace();
- }
- return mode;
- }
-
-
-
-
-
-
- public static int getScreenBrightness() {
- int screenBrightness = -1;
- try {
- screenBrightness = Settings.System.getInt(APP.context.getContentResolver(),
- Settings.System.SCREEN_BRIGHTNESS);
- } catch (Settings.SettingNotFoundException e) {
- e.printStackTrace();
- }
- return screenBrightness;
- }
-
-
-
-
-
-
- public static void setScreenMode(int mode) {
- try {
- Settings.System.putInt(APP.context.getContentResolver(),
- Settings.System.SCREEN_BRIGHTNESS_MODE, mode);
- Uri uri = Settings.System
- .getUriFor("screen_brightness_mode");
- APP.context.getContentResolver().notifyChange(uri, null);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-
-
-
-
-
-
- public static void setScreenBrightness(int paramInt) {
- Settings.System.putInt(APP.context.getContentResolver(),
- Settings.System.SCREEN_BRIGHTNESS, paramInt);
- Uri uri = Settings.System
- .getUriFor("screen_brightness");
- APP.context.getContentResolver().notifyChange(uri, null);
- }
- }
其中APP是我自定义的Application,context是其引用。至于context是什么我在这里就先不解释了。
代码直接复制下来,稍作修改和导包就可以直接使用。
注意setScreenBrightness()方法需要如下权限
- <uses-permission android:name="android.permission.WRITE_SETTINGS" />
然后就是第二种情况的代码
- public class activityBrightnessManager{
-
-
-
-
-
-
-
- public static void setActivityBrightness(float paramFloat, Activity activity) {
- Window localWindow = activity.getWindow();
- WindowManager.LayoutParams params = localWindow.getAttributes();
- params.screenBrightness = paramFloat;
- localWindow.setAttributes(params);
- }
-
-
-
-
-
-
-
- public static float getActivityBrightness(Activity activity) {
- Window localWindow = activity.getWindow();
- WindowManager.LayoutParams params = localWindow.getAttributes();
- return params.screenBrightness;
- }
- }
坑就在这里:
setActivityBrightness()方法
1、这里设置传入的参数是0-1.0f。
2、一旦传入参数,则当前的亮度属性完全独立,不会受到全局亮度属性的影响,并且没有自动模式。
3、当传入参数-1.0f,当前的activity就又会重新使用全局的亮度属性。
getActivityBrightness()方法
1、在没有设置属性值之前,默认返回的是-1.0。代表使用全局亮度属性。
2、设置属性值之后,返回的是当前属性值。