Home > Java > javaTutorial > body text

How to Programmatically Adjust Screen Brightness on Android?

DDD
Release: 2024-10-25 06:31:02
Original
407 people have browsed it

How to Programmatically Adjust Screen Brightness on Android?

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>
Copy after login

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>
Copy after login

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>
Copy after login

Don't forget to include the necessary permission in your manifest:

<code class="xml"><uses-permission android:name="android.permission.WRITE_SETTINGS" /></code>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template