|
| 1 | +package kv.vension.fastframe.utils |
| 2 | + |
| 3 | +import android.app.Activity |
| 4 | +import android.content.Context |
| 5 | +import android.provider.Settings |
| 6 | + |
| 7 | +/** |
| 8 | + * Introduction : 屏幕亮度工具类 brightness 0-255之间 |
| 9 | + * 所需权限 |
| 10 | + * <uses-permission android:name="android.permission.CHANGE_CONFIGURATION"></uses-permission> |
| 11 | + * <uses-permission android:name="android.permission.WRITE_SETTINGS"></uses-permission> |
| 12 | + */ |
| 13 | +object BrightnessUtil { |
| 14 | + |
| 15 | + /** |
| 16 | + * 判断是否开启了自动亮度调节 |
| 17 | + */ |
| 18 | + fun isAutoBrightness(context: Context): Boolean { |
| 19 | + val resolver = context.contentResolver |
| 20 | + var automicBrightness = false |
| 21 | + try { |
| 22 | + automicBrightness = Settings.System.getInt( |
| 23 | + resolver, |
| 24 | + Settings.System.SCREEN_BRIGHTNESS_MODE |
| 25 | + ) == Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC |
| 26 | + } catch (e: Settings.SettingNotFoundException) { |
| 27 | + e.printStackTrace() |
| 28 | + } |
| 29 | + |
| 30 | + return automicBrightness |
| 31 | + } |
| 32 | + |
| 33 | + /** |
| 34 | + * 获取当前屏幕亮度 |
| 35 | + */ |
| 36 | + fun getScreenBrightness(context: Context): Int { |
| 37 | + var nowBrightnessValue = 0 |
| 38 | + val resolver = context.contentResolver |
| 39 | + try { |
| 40 | + nowBrightnessValue = Settings.System.getInt(resolver, Settings.System.SCREEN_BRIGHTNESS) |
| 41 | + } catch (e: Exception) { |
| 42 | + e.printStackTrace() |
| 43 | + } |
| 44 | + |
| 45 | + return nowBrightnessValue |
| 46 | + } |
| 47 | + |
| 48 | + /** |
| 49 | + * 关闭自动亮度调节 |
| 50 | + */ |
| 51 | + fun autoBrightness(activity: Context, flag: Boolean): Boolean { |
| 52 | + var value = 0 |
| 53 | + if (flag) { |
| 54 | + value = Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC //开启 |
| 55 | + } else { |
| 56 | + value = Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL//关闭 |
| 57 | + } |
| 58 | + return Settings.System.putInt( |
| 59 | + activity.contentResolver, |
| 60 | + Settings.System.SCREEN_BRIGHTNESS_MODE, |
| 61 | + value |
| 62 | + ) |
| 63 | + } |
| 64 | + |
| 65 | + /** |
| 66 | + * 设置亮度,退出app也能保持该亮度值 |
| 67 | + */ |
| 68 | + fun saveBrightness(context: Context, brightness: Int) { |
| 69 | + val resolver = context.contentResolver |
| 70 | + val uri = Settings.System.getUriFor(Settings.System.SCREEN_BRIGHTNESS) |
| 71 | + Settings.System.putInt(resolver, Settings.System.SCREEN_BRIGHTNESS, brightness) |
| 72 | + resolver.notifyChange(uri, null) |
| 73 | + } |
| 74 | + |
| 75 | + /** |
| 76 | + * 设置当前activity显示的亮度 |
| 77 | + */ |
| 78 | + fun setBrightness(activity: Activity, brightness: Int) { |
| 79 | + val lp = activity.window.attributes |
| 80 | + lp.screenBrightness = java.lang.Float.valueOf(brightness.toFloat()) * (1f / 255f) |
| 81 | + activity.window.attributes = lp |
| 82 | + } |
| 83 | +} |
0 commit comments