1、SavedStateHandle(进程被杀保存数据)
1、依赖
在build.gradle的dependencies中添加依赖:
implementation 'androidx.lifecycle:lifecycle-viewmodel-savedstate:1.0.0-alpha01'
2、MyViewModel的写法
public class MyViewModel extends ViewModel { private SavedStateHandle handle; public MyViewModel(SavedStateHandle handle){ this.handle = handle; } public MutableLiveData<Integer> getNumber(){ if (!handle.contains(MainActivity.KEY)){ handle.set(MainActivity.KEY,0); } return handle.getLiveData(MainActivity.KEY); } public void add(){ getNumber().setValue(getNumber().getValue()+1); } }
-
此时不使用livedata来保存数据,使用SavedStateHandle。
-
构造函数需要初始化,在主函数中初始化viewModel时会传进来相应的数据。
-
这个就相当于一个Map,一个关键字对应一个数据。
-
getNumber()返回的是一个livedata类型的数据。
3、主函数的写法
public class MainActivity extends AppCompatActivity { ActivityMainBinding binding; MyViewModel myViewModel; public final static String KEY = "my_number"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); binding = DataBindingUtil.setContentView(this,R.layout.activity_main); myViewModel = ViewModelProviders.of(this,new SavedStateVMFactory(this)).get(MyViewModel.class); binding.setData(myViewModel); binding.setLifecycleOwner(this); } }
-
此时viewmodel创建时需要传递一个参数给构造函数。
4、总结
该方法用于进程被杀死的情况恢复数据,如果用户退出程序,那么数据还是不存在的。
2、SharedPreferences(数据的存储)
SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putInt("NUMBER",100); editor.apply();
一般写法,创建一个与本activity名称相同的存储文件,存储关键字为NUMBER的数据,值为100。
editor.apply();是异步提交。
如果MyViewModel继承的是AndroidViewModel的话,则关机、退出等都可以保存数据。
myviewmodel代码:
public class MyViewModel extends AndroidViewModel { private SavedStateHandle handle; final String Number = "NUMBER"; public MyViewModel(@NonNull Application application, SavedStateHandle handle) { super(application); this.handle = handle; if (!handle.contains(Number)){ load(); } } public MutableLiveData<Integer> getNumber(){ return handle.getLiveData(Number); } private void load(){ SharedPreferences shp = getApplication().getSharedPreferences("MyData", Context.MODE_PRIVATE); int x = shp.getInt(Number,0); handle.set(Number,x); } public void save(){ SharedPreferences shp = getApplication().getSharedPreferences("MyData", Context.MODE_PRIVATE); SharedPreferences.Editor editor = shp.edit(); editor.putInt(Number,getNumber().getValue()); editor.apply(); } public void dowhat(int x){ handle.set(Number,getNumber().getValue()+x); } }
主进程代码:
public class MainActivity extends AppCompatActivity { MyViewModel myViewModel; ActivityMainBinding binding; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); binding = DataBindingUtil.setContentView(this,R.layout.activity_main); myViewModel = ViewModelProviders.of(this,new SavedStateVMFactory(this)).get(MyViewModel.class); binding.setData(myViewModel); binding.setLifecycleOwner(this); } @Override protected void onPause() { super.onPause(); myViewModel.save(); } }