Can't apply system screen brightness programmatically in Android

后端 未结 4 2058
闹比i
闹比i 2020-11-28 11:24

I\'m using the following to set the system auto brightness mode and level:

    android.provider.Settings.System.putInt(y.getContentResolver(),Settings.System         


        
4条回答
  •  执念已碎
    2020-11-28 12:04

    I created a static method in my Application class which I invoke from all my Activity.onResume() methods.

    MyApplication extends Application {
        ...
        public static void setBrightness(final Activity context) {
            // get the content resolver
            final ContentResolver cResolver = context.getContentResolver();
            // get the current window
            final Window window = context.getWindow();
    
            try {
                // get the current system brightness
                int brightnessLevel = System.getInt(cResolver,System.SCREEN_BRIGHTNESS);
                // get the current window attributes
                LayoutParams layoutpars = window.getAttributes();
                // set the brightness of this window
                layoutpars.screenBrightness = brightnessLevel / (float) 255;
                // apply attribute changes to this window
                window.setAttributes(layoutpars);
            } catch (SettingNotFoundException e) {
                // throw an error cuz System.SCREEN_BRIGHTNESS couldn't be retrieved
                Log.e("Error", "Cannot access system brightness");
                e.printStackTrace();
            }
        }
    }
    
    MyActivity extends Activity {
        ...
        public void onResume() {
            super.onResume();
            Log.d(TAG, "onResume()");
            MyApplication.setBrightness(this);
        }
    }
    

提交回复
热议问题