shared preferences是什么?就是数据的持久化,主要保存一些简单的数据在应用内部
定义变量:
private Button mButton;
private boolean mDatas;
调用函数
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
setData();
saveDataPreference(mDatas);
}
private void setData() {
SharedPreferences sharedPreferences =FirstActivity.this.getSharedPreferences("preference_name", Context.MODE_PRIVATE);
mDatas = sharedPreferences.getBoolean("mData", true);
if (mDatas == false) {
startActivity(new Intent(FirstActivity.this, MainActivity.class));
finish();
}
else {
mButton = (Button) findViewById(R.id.button1);
mButton.setOnClickListener(new View.OnClickListener() { ;
@Override
public void onClick(View view) {
startActivity(new Intent(FirstActivity.this, SecondActivity.class));
FirstActivity.this.finish();
}
});
private void saveDataPreference(boolean data){
//系统会自动帮我们创建一个XML文件 名字是"preference_name "
SharedPreferences sharedPreferences = FirstActivity.this.getSharedPreferences("preference_name", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("mData",false);
editor.commit();
}