使用viewModel保存数据,使App被系统kill后,再次启动依然可以恢复被kill前的数据
下面的
model = ViewModelProviders.of(this,new SavedStateViewModelFactory(this)).get(MyViewModel.class);
api过时了,没有此方法了,仅记录下实现保存数据的思路
1.导入
implementation 'androidx.lifecycle:lifecycle-viewmodel-savedstate:1.0.0-alpha01'
2.定义构造函数
导入lifecycle-viewmodel-savedstate后ViewModel中可以使用带有一个参数的构造函数
private MyViewModel(SavedStateHandle handle){
this.handle = handle;
}
public MutableLiveData<Integer> getNumber() {
if(!handle.contains(MainActivity.KEY_NUMBER)){
handle.set(MainActivity.KEY_NUMBER,0);
}
return handle.getLiveData(MainActivity.KEY_NUMBER);
}
//定义方法保存数据
public void add(){
getNumber().setValue(getNumber().getValue() + 1);
}
3.在Activity中的代码调整
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.SavedStateViewModelFactory;
import androidx.lifecycle.ViewModelProviders;
import android.os.Bundle;
import com.gao.viewmodelrestore.databinding.ActivityMainBinding;
public class MainActivity extends AppCompatActivity {
MyViewModel model;
ActivityMainBinding binding;
public static final String KEY_NUMBER = "key_number";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
// model = ViewModelProviders.of(this).get(MyViewModel.class);
//下面的api过时了,不能用了
model = ViewModelProviders.of(this,new SavedStateViewModelFactory(this)).get(MyViewModel.class);
binding.setData(model);
binding.setLifecycleOwner(this);
}
}
网友评论