How do you get the current screen brightness of your activity?
Following method works fine for setting the brightness to max by calling setBrightness(100)
:
private void setBrightness(int brightness) {
WindowManager.LayoutParams layoutParams = getWindow().getAttributes();
layoutParams.screenBrightness = brightness/100.0f;
getWindow().setAttributes(layout开发者_StackOverflow中文版Params);
}
Im trying to achieve the following:
- Start the activity and save the current brightness value
- Set brightness to max
- Reset brightness to the initial value on certain events
Many thanks!
Try
int curBrightnessValue = android.provider.Settings.System.getInt(getContentResolver(), android.provider.Settings.System.SCREEN_BRIGHTNESS);
and then
WindowManager.LayoutParams layoutParams = getWindow().getAttributes();
layoutParams.screenBrightness = curBrightnessValue/100.0f;
getWindow().setAttributes(layoutParams);
To reset brightness to default value
WindowManager.LayoutParams layoutParams = getWindow().getAttributes();
layoutParams.screenBrightness = -1f;
getWindow().setAttributes(layoutParams);
A value of less than 0, the default, means to use the preferred screen brightness.
Refer http://developer.android.com/reference/android/view/WindowManager.LayoutParams.html#screenBrightness
I use this on Android 17+ (Probably works w/lower APIs)
private void setScreenBrightnessTo(float brightness) {
WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
if (lp.screenBrightness == brightness) {
return;
}
lp.screenBrightness = brightness;
getActivity().getWindow().setAttributes(lp);
}
Usages:
To set screen to MAX Brightness (for example when you show a Barcode or something):
setScreenBrightnessTo(BRIGHTNESS_OVERRIDE_FULL);
To RESET back to whatever the user had before:
setScreenBrightnessTo(BRIGHTNESS_OVERRIDE_NONE);
There are distinct brightness values: 1) if you already set something for activity brightness, you can get this value. If not set it will be -1F 2) system value for brightness Example to get it:
val activityBrightness = requireActivity().window.attributes.screenBrightness
val systemBrightness = Settings.System.getInt(requireActivity().contentResolver, Settings.System.SCREEN_BRIGHTNESS) / 255
currentBrightness = if (activityBrightness == -1F) systemBrightness.toFloat() * 100 else activityBrightness * 100
Example code to set brightness for activity window (bear in mind that value can be from 0.0 to 1.0):
currentBrightness = if (currentBrightness < 0) 0.0F else if (currentBrightness > 100) 100.0F else currentBrightness
val layoutParams = activity?.window?.attributes
if (layoutParams != null) {
layoutParams.screenBrightness = currentBrightness / 100
requireActivity().window.attributes = layoutParams
}
精彩评论