XML文件:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.screenofftime.MainActivity"
android:gravity="center_horizontal" >
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="选择屏幕休眠时间"
android:onClick="chooseTime"/>
</LinearLayout>
MainActivity:
package com.example.screenofftime;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.provider.Settings;
import android.view.View;
import android.content.DialogInterface.OnClickListener;
public class MainActivity extends Activity {
private SharedPreferences sp;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sp = getSharedPreferences("lastChoice",Activity.MODE_PRIVATE);
}
public void chooseTime(View v){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setTitle("选择背光时间");
final String[] onScreenTime =new String[] {"15秒","30秒","1分钟","2分钟","5分钟","10分钟"};
int lastChoice = sp.getInt("time", -1);
/**
* 第二个参数表示默认选中的item的下标 -1代表没有默认的选项,设置为上次默认选中项
*
*/
alertDialog.setSingleChoiceItems(onScreenTime, lastChoice, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
setScreenOffTime(15000);
saveLastChoice(which);
break;
case 1:
setScreenOffTime(30000);
saveLastChoice(which);
break;
case 2:
setScreenOffTime(60000);
saveLastChoice(which);
break;
case 3:
setScreenOffTime(120000);
saveLastChoice(which);
break;
case 4:
setScreenOffTime(300000);
saveLastChoice(which);
break;
case 5:
setScreenOffTime(600000);
saveLastChoice(which);
break;
default:
break;
}
}
});
alertDialog.setNegativeButton("取消", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
alertDialog.setPositiveButton("确定", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
alertDialog.create().show();
}
/***
* 设置背光时间
* @param paramInt
*/
private void setScreenOffTime(int paramInt) {
try {
Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT,paramInt);
} catch (Exception localException) {
localException.printStackTrace();
}
}
/***
* 将上次选择保存到SharedPreferences中,下次打开时默认选中上次所选项
* @param which
*/
private void saveLastChoice(int which){
Editor edit = sp.edit();
edit.putInt("time", which);
edit.commit();
}
}
