Programmatically Modify System Brightness
To adjust the brightness of your device's screen programmatically, you can utilize various approaches. One common method is to handle the screen brightness attributes:
<code class="java">WindowManager.LayoutParams lp = window.getAttributes(); lp.screenBrightness = (float)brightness; window.setAttributes(lp);</code>
However, this technique might not always work due to potential limitations or incorrect max value settings.
An alternative approach is to leverage the system settings and ContentResolver:
<code class="java">private ContentResolver cResolver; private Window window; private int brightness; onCreate() { cResolver = getContentResolver(); window = getWindow(); try { // Handle auto brightness mode Settings.System.putInt(cResolver, Settings.System.SCREEN_BRIGHTNESS_MODE, Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL); // Retrieve current brightness brightness = Settings.System.getInt(cResolver, Settings.System.SCREEN_BRIGHTNESS); } catch (SettingNotFoundException e) { Log.e("Error", "Cannot access system brightness"); e.printStackTrace(); } }</code>
You can then adjust the brightness:
<code class="java">// Update system brightness Settings.System.putInt(cResolver, Settings.System.SCREEN_BRIGHTNESS, brightness); // Update window brightness attributes LayoutParams layoutpars = window.getAttributes(); layoutpars.screenBrightness = brightness / 255f; window.setAttributes(layoutpars);</code>
Don't forget to include the necessary permission in your manifest:
<code class="xml"><uses-permission android:name="android.permission.WRITE_SETTINGS" /></code>
For API level 23 and above, you need to request permission through Settings Activity as described in the documentation.
The above is the detailed content of How to Programmatically Adjust Screen Brightness on Android?. For more information, please follow other related articles on the PHP Chinese website!