The following is my working code (as a widget):
Basically, it starts an operation that performs the setup.
BrightnessActivity.java:
package com.xxx.switchwidget; import com.xxx.Utils; import android.app.Activity; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.WindowManager; public class BrightnessActivity extends Activity { private static final boolean DEBUG = true; private static final String TAG = "BrightnessActivity"; private Handler mHandler = new Handler() { public void handleMessage(Message msg) { finish(); } }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); int brightness = SwitchWidget.getNextBrightness(this); if (brightness < 0) { finish(); return; } WindowManager.LayoutParams params = getWindow().getAttributes(); params.screenBrightness = Float.valueOf(brightness / Float.valueOf(SwitchWidget.MAXIMUM_BACKLIGHT)).floatValue(); getWindow().setAttributes(params); toggleBrightness(); } @Override public void onDestroy() { super.onDestroy(); if (DEBUG) Utils.log(TAG, "onDestroy()"); } private void toggleBrightness() { new AsyncTask<Void, Integer, Void>() { @Override protected Void doInBackground(Void... args) { SwitchWidget.toggleBrightness(BrightnessActivity.this);
And the method in your activity (tab): (this is my * SwitchWidget in my code) *
public static void toggleBrightness(Context context) { try { ContentResolver cr = context.getContentResolver(); int brightness = Settings.System.getInt(cr, Settings.System.SCREEN_BRIGHTNESS); boolean isBrightnessModeChanged = false; int brightnessMode = Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL; brightnessMode = Settings.System.getInt(cr, Settings.System.SCREEN_BRIGHTNESS_MODE); // Rotate AUTO -> MINIMUM -> DEFAULT -> MAXIMUM // Technically, not a toggle... if (brightnessMode == Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC) { brightness = DEFAULT_BACKLIGHT; brightnessMode = Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL; isBrightnessModeChanged = true; } else if (brightness < DEFAULT_BACKLIGHT) { brightness = DEFAULT_BACKLIGHT; } else if (brightness < MAXIMUM_BACKLIGHT) { brightness = MAXIMUM_BACKLIGHT; } else { brightness = MINIMUM_BACKLIGHT; } // Set screen brightness mode (automatic or manual) if (isBrightnessModeChanged) { Settings.System.putInt(context.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS_MODE, brightnessMode); } if (brightnessMode == Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL) { Settings.System.putInt(cr, Settings.System.SCREEN_BRIGHTNESS, brightness); } } catch (Settings.SettingNotFoundException e) { if (DEBUG) Utils.log(TAG, "toggleBrightness: " + e); } }
Finally, call this to set the brightness:
Intent newIntent = new Intent(mContext, BrightnessActivity.class); newIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); mContext.startActivity(newIntent);
Wish it helps.
source share