Android screen brightness adjustment code
- 2020-06-15 10:13:26
- OfStack
To adjust the screen brightness, first set the current activity brightness and then save it as system brightness.
1. Check system brightness in onCreate() and set seekBar:
private void screenBrightness_check()
{
// First turn off the automatic brightness adjustment of the system
try
{
if(android.provider.Settings.System.getInt(getContentResolver(),android.provider.Settings.System.SCREEN_BRIGHTNESS_MODE) == android.provider.Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC)
{
android.provider.Settings.System.putInt(getContentResolver(),
android.provider.Settings.System.SCREEN_BRIGHTNESS_MODE,
android.provider.Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
}
}
catch (SettingNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
// Get current brightness , Returns if the fetch fails 255
intScreenBrightness=(int)(android.provider.Settings.System.getInt(getContentResolver(),
android.provider.Settings.System.SCREEN_BRIGHTNESS,
255));
// Text, progress bar display
mSeekBar_light.setProgress(intScreenBrightness);
mTextView_light.setText(""+intScreenBrightness*100/255);
}
2. When dragging seekBar, set the current activity brightness and save it as system brightness:
// The screen brightness
private void setScreenBritness(int brightness)
{
// Keep the screen dark
if(brightness<=1)
{
brightness=1;
}
// Set the current activity Screen brightness of
WindowManager.LayoutParams lp = this.getWindow().getAttributes();
//0 to 1, Adjust the brightness to full brightness
lp.screenBrightness = Float.valueOf(brightness/255f);
this.getWindow().setAttributes(lp);
// Save as system brightness method 1
android.provider.Settings.System.putInt(getContentResolver(),
android.provider.Settings.System.SCREEN_BRIGHTNESS,
brightness);
// Save as system brightness method 2
// Uri uri = android.provider.Settings.System.getUriFor("screen_brightness");
// android.provider.Settings.System.putInt(getContentResolver(), "screen_brightness", brightness);
// // resolver.registerContentObserver(uri, true, myContentObserver);
// getContentResolver().notifyChange(uri, null);
// Change brightness text display
mTextView_light.setText(""+brightness*100/255);
}