Wednesday, February 2, 2011

Change Android Screen Brightness, LayoutParams.screenBrightness

To change the backlight brightness, LayoutParams.screenBrightness can be used.

WindowManager.LayoutParams layoutParams = getWindow().getAttributes();
layoutParams.screenBrightness = BackLightValue;
getWindow().setAttributes(layoutParams);

This can be used to override the user's preferred brightness of the screen. A value of less than 0, the default, means to use the preferred screen brightness. 0 to 1 adjusts the brightness from dark to full bright.

Change Android Screen Brightness

package com.exercise.AndroidScreenBrightness;

import android.app.Activity;
import android.os.Bundle;
import android.view.WindowManager;
import android.widget.SeekBar;
import android.widget.TextView;

public class AndroidScreenBrightness extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

SeekBar BackLightControl = (SeekBar)findViewById(R.id.backlightcontrol);
final TextView BackLightSetting = (TextView)findViewById(R.id.backlightsetting);

BackLightControl.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener(){

@Override
public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
// TODO Auto-generated method stub
float BackLightValue = (float)arg1/100;
BackLightSetting.setText(String.valueOf(BackLightValue));

WindowManager.LayoutParams layoutParams = getWindow().getAttributes();
layoutParams.screenBrightness = BackLightValue;
getWindow().setAttributes(layoutParams);


}

@Override
public void onStartTrackingTouch(SeekBar arg0) {
// TODO Auto-generated method stub

}

@Override
public void onStopTrackingTouch(SeekBar arg0) {
// TODO Auto-generated method stub

}});
}
}


main.xml, layout with a SeekBar to change backlight brightness.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Set BackLight of the App"
/>
<SeekBar
android:id="@+id/backlightcontrol"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="10px"
android:max="100"
android:progress="50"
/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/backlightsetting"
android:text="0.50"
/>
</LinearLayout>


Download the files.

next:
- Change system screen brightness, using android.provider.Settings.System.SCREEN_BRIGHTNESS

1 comment:

Yusuf said...

when the value becomes 0 the screen switches off. so how can i set the min value greater than 0?
thank you