现实生活中,在每个APP中,总会有调节屏幕亮度的需求~
这里是使用SeekBar来调节手机屏幕亮度的,学过手势之后,就可以手势控制亮度了~后面有机会在说~
核心代码如下:
public class MainActivity extends Activity {
private SeekBar seekBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
seekBar = (SeekBar) findViewById(R.id.sb);
seekBar.setMax(255);
int normal = Settings.System.getInt(getContentResolver(),
Settings.System.SCREEN_BRIGHTNESS, 255);
seekBar.setProgress(normal);
seekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
//当Seekbar在滑动的时候,亮度也随着变化
@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
int tmpInt = progress;
// 当进度小于80时,设置成80,防止太黑看不见的后果。
if (tmpInt < 80) {
tmpInt = 80;
}
// 根据当前进度改变亮度
Settings.System.putInt(getContentResolver(),
Settings.System.SCREEN_BRIGHTNESS, progress);
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);
}
});
}
}
布局文件就一个SeekBar,就不贴代码了~
需要加权限,因为调节亮度是手机自带的功能
<uses-permission android:name="android.permission.WRITE_SETTINGS"/>
源码:http://download.csdn.net/detail/qq_33642117/9585012