首先要添加系统权限<uses-permission android:name="android.permission.WRITE_SETTINGS" />
Activity里面的代码如下
seekBar = (SeekBar)layout.findViewById(R.id.seekBar1);
text2 = (TextView)layout.findViewById(R.id.textView3);
checkbox = (CheckBox)layout.findViewById(R.id.checkBox1);
//进度条绑定最大亮度,255是最大亮度
seekBar.setMax(255);
//取得当前亮度
int normal = Settings.System.getInt(getContentResolver(),
Settings.System.SCREEN_BRIGHTNESS, 255);
text2.setText(String.valueOf(normal));
//进度条绑定当前亮度
seekBar.setProgress(normal);
seekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
//取得当前进度
checkbox.setChecked(false);
int tmpInt = seekBar.getProgress();
text2.setText(String.valueOf(tmpInt));
//当进度小于80时,设置成80,防止太黑看不见的后果。
if (tmpInt < 40) {
tmpInt = 40;
}
//根据当前进度改变亮度
Settings.System.putInt(getContentResolver(),
Settings.System.SCREEN_BRIGHTNESS, tmpInt);
tmpInt = Settings.System.getInt(getContentResolver(),
Settings.System.SCREEN_BRIGHTNESS, -1);
WindowManager.LayoutParams wl = getWindow()
.getAttributes();
float tmpFloat = (float) tmpInt / 255;
if (tmpFloat > 0 && tmpFloat <= 1) {
wl.screenBrightness = tmpFloat;
}
getWindow().setAttributes(wl);
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
}
});
checkbox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
// TODO 自动生成的方法存根
text2.setText("150");
int light = 150;
Settings.System.putInt(getContentResolver(),
Settings.System.SCREEN_BRIGHTNESS, light);
light = Settings.System.getInt(getContentResolver(),
Settings.System.SCREEN_BRIGHTNESS, -1);
WindowManager.LayoutParams wl = getWindow()
.getAttributes();
float tmpFloat = (float) light / 255;
if (tmpFloat > 0 && tmpFloat <= 1) {
wl.screenBrightness = tmpFloat;
}
getWindow().setAttributes(wl);
}
});
xml的代码
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:text="背景亮度为:" />
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
<SeekBar
android:id="@+id/seekBar1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
<CheckBox
android:id="@+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="false"
android:text="默认亮度" />
</LinearLayout>