Changing screen brightness programmatically (as with the power widget)

Lukap picture Lukap · Oct 4, 2011 · Viewed 66.8k times · Source

I was searching how to change the brightness of the screen programmatically and I found this it is very good solution and it works nice, but it works only while my app is active. After my application is shutdown then the brightness is returned back the the same value as before I start my app.

I want to be able to change the brightness just like when I press on the brightness button from my power widget. In the power widget that comes from android there are 3 states. One very bright one very dark and one in between. Is it possible to change the brightness just like when someone press on this widget ?

enter image description here

Edit1: I created this and I added permision to my manifest but when the app is started I do not see any changes to the brightness, I tried with 10 with 100 and now with 200 but no changes any suggestions ?

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
android.provider.Settings.System.putInt(this.getContentResolver(),
        android.provider.Settings.System.SCREEN_BRIGHTNESS, 200);
}

Answer

Lukap picture Lukap · Oct 5, 2011

This is the complete code I found to be working:

Settings.System.putInt(this.getContentResolver(),
        Settings.System.SCREEN_BRIGHTNESS, 20);

WindowManager.LayoutParams lp = getWindow().getAttributes();
lp.screenBrightness =0.2f;// 100 / 100.0f;
getWindow().setAttributes(lp);

startActivity(new Intent(this,RefreshScreen.class));

The code from my question does not work because the screen doesn't get refreshed. So one hack on refreshing the screen is starting dummy activity and than in on create of that dummy activity to call finish() so the changes of the brightness take effect.