//继承AndroidViewModel可以直接访问系统资源和SharedPreferences
public class MyViewModel extends AndroidViewModel {
// // 这里也可以定义context
// Application application;
SavedStateHandle handle;
String key = getApplication().getResources().getString(R.string.data_key);
String shpname = getApplication().getResources().getString(R.string.shp_name);
public MyViewModel(@NonNull Application application, SavedStateHandle handle) {
super(application);
this.handle = handle;
if (!handle.contains(key)) {
load();
}
}
public LiveData<Integer> getNumber() {
return handle.getLiveData(key);
}
public void load() {
SharedPreferences shp = getApplication().getSharedPreferences(shpname, Context.MODE_PRIVATE);
int x = shp.getInt(key, 0);
handle.set(key, x);
}
public void save() {
SharedPreferences shp = getApplication().getSharedPreferences(shpname, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = shp.edit();
editor.putInt(key, getNumber().getValue());
editor.apply();
}
public void add(int x) {
handle.set(key, getNumber().getValue() == null ? 0 : getNumber().getValue() + x);
//save();
}
}
public class MainActivity extends AppCompatActivity {
MyViewModel myViewModel;
ActivityMainBinding binding;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
binding = DataBindingUtil.setContentView(this,R.layout.activity_main);
// 如果是定义了context 这里就获取context
// myViewModel.application = getApplication();
myViewModel = new ViewModelProvider(this).get(MyViewModel.class);
binding.setData(myViewModel);
binding.setLifecycleOwner(this);
}
//在onPause时保存
@Override
protected void onPause() {
super.onPause();
myViewModel.save();
}
}