main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <Button android:id="@+id/plus" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="+" android:onClick="onclick" /> <Button android:id="@+id/minus" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="-" android:onClick="onclick" /> <TextView android:id="@+id/tv" android:layout_width="fill_parent" android:layout_height="wrap_content" /> </LinearLayout>
BrightnessActivity
public class BrightnessActivity extends Activity {
private static final String TAG = "BrightnessActivity";
private TextView tv;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void onclick(View v) {
try {
// 取得螢幕亮度
int brightness = Settings.System.getInt(getContentResolver(),
Settings.System.SCREEN_BRIGHTNESS);
String msg = "目前亮度 - " + brightness;
Log.d(BrightnessActivity.TAG, msg);
this.insert2Tv(msg);
switch (v.getId()) {
case R.id.plus:
brightness += 30;
break;
case R.id.minus:
brightness -= 30;
break;
}
// 亮度範圍為 0 - 255
brightness = Math.min(brightness, 255);
brightness = Math.max(brightness, 0);
// 設定螢幕亮度
Settings.System.putInt(getContentResolver(),
Settings.System.SCREEN_BRIGHTNESS, brightness);
msg = "調整後亮度 - " + brightness;
Log.d(BrightnessActivity.TAG, msg);
this.insert2Tv(msg);
}
catch (SettingNotFoundException e) {
Log.e(BrightnessActivity.TAG, e.getMessage(), e);
this.insert2Tv(e.getMessage());
}
}
private void insert2Tv(String msg) {
if (this.tv == null) {
this.tv = (TextView) this.findViewById(R.id.tv);
}
this.tv.setText(msg + "\n" + this.tv.getText().toString());
}
}最後再加上 android.permission.WRITE_SETTINGS 權限就可以了。

沒有留言:
張貼留言