简体   繁体   中英

changing screen brightness via android app

I have the same need like this , but I found the answer under that question aren't work.

I want to make buttons to change my screen brightness while my app is running.

I have found this code, but it doesn't work if I copy this code into my mainActivity directly.

WindowManager.LayoutParams lp = getWindow().getAttributes();
float brightness=1.0f;
lp.screenBrightness = brightness;
getWindow().setAttributes(lp);

I use android studio and API level is 21 and I added user permission.

This piece code is the nearest to my target, who can help me run this code?

This worked for me:

In onCreate() method write this,

private int brightness;

try{
    Settings.System.putInt(getContentResolver(),
                           Settings.System.SCREEN_BRIGHTNESS_MODE,
                           Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);

    brightness = Settings.System.getInt(getContentResolver(), 
                               Settings.System.SCREEN_BRIGHTNESS);
}
catch(SettingNotFoundException e){
    Log.e("Error", "Cannot access system brightness");
    e.printStackTrace();
}

To update the brightness,

Settings.System.putInt(getContentResolver(), System.SCREEN_BRIGHTNESS, brightness);
LayoutParams layoutpars = getWindow().getAttributes();
layoutpars.screenBrightness = brightness / (float)255;
getWindow().setAttributes(layoutpars);

Permission in manifest,

<uses-permission android:name="android.permission.WRITE_SETTINGS"></uses-permission>

If you read that question carefully you'll find that you need to refresh your activity and one possible solution to refresh your activity (as mentioned in that answer too) is to create a dummy activity, start it and that finish in in its onCreate() method. you also need this permission in your manifest:

 <uses-permission android:name="android.permission.WRITE_SETTINGS" />

Window#mWindowAttributes screenBrightness 0 到 1 调节亮度从暗到全亮

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM