布局就是两个按钮,通过两个按钮一个读一个写
public class MainActivity extends Activity {
SharedPreferences preferences;
SharedPreferences.Editor editor;
Button sread,swrite;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
preferences = getSharedPreferences("pmit",MODE_WORLD_READABLE);
editor = preferences.edit();
sread=(Button) findViewById(R.id.spreferences_read);
swrite=(Button) findViewById(R.id.spreferences_write);
//记录程序使用次数
int count =preferences.getInt("count", 0);
Toast.makeText(this, "程序被使用了"+ count +"次", 10000).show();
editor.putInt("count", ++count);
editor.commit();
//设置对按钮的响应
sread.setOnClickListener(new OnClickListener(){
public void onClick(View arg0) {
//
String time =preferences.getString("time", null);
int randNum = preferences.getInt("random", 0);
String result = time == null ? "您暂时还没有写入数据 " :
"写入时间 " + time + "\n上次生成的随机数为:" + randNum;
}
});
swrite.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日" +"hh:mm:ss");
//存入当前时间和随机数
editor.putString("time", sdf.format(new Date()));
editor.putInt("random", (int) (Math.random()*100));
editor.commit();
}
});
}
}
SharedPreferences 的三种权限
1.Context.MODE_PRIVATE 只能在本应用程序读写
2.Context.MODE_WORLD_READABLE 能被其他应用读
3.Context.MODE_WORLD_WRITEABLE 能被其他应用读写