set Screen Brightness And Apply - Android android.provider

Android examples for android.provider:Settings

Description

set Screen Brightness And Apply

Demo Code

import android.app.Activity;
import android.content.Context;
import android.provider.Settings;
import android.view.Window;
import android.view.WindowManager;

public class Main {

  public static boolean setScreenBrightnessAndApply(Activity activity, int screenBrightness) {
    boolean result = true;
    result = setScreenBrightness(activity, screenBrightness);
    if (result) {
      setWindowBrightness(activity, screenBrightness);
    }/*from   w  ww .j  ava  2 s .  c  o m*/
    return result;
  }

  public static boolean setScreenBrightness(Context context, int screenBrightness) {
    int brightness = screenBrightness;
    if (screenBrightness < 1) {
      brightness = 1;
    } else if (screenBrightness > 255) {
      brightness = screenBrightness % 255;
      if (brightness == 0) {
        brightness = 255;
      }
    }
    boolean result = Settings.System.putInt(context.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS,
        brightness);
    return result;
  }

  public static void setWindowBrightness(Activity activity, float screenBrightness) {
    float brightness = screenBrightness;
    if (screenBrightness < 1) {
      brightness = 1;
    } else if (screenBrightness > 255) {
      brightness = screenBrightness % 255;
      if (brightness == 0) {
        brightness = 255;
      }
    }
    Window window = activity.getWindow();
    WindowManager.LayoutParams localLayoutParams = window.getAttributes();
    localLayoutParams.screenBrightness = (float) brightness / 255;
    window.setAttributes(localLayoutParams);
  }

}

Related Tutorials