android----AndroidViewModel访问SharedPreference,重启手机数据也存在
这几天一直学习android的保存数据,今天来认识一下更强的保存数据。
之前用ViewModel保存数据,屏幕反转,或者回到主界面都可以保存,但是如果退出或者重启手机就不行,今天就来完成这一功能。
之前我们创建的My View Model都是继承View Model,今天是继承Android View Model,原因是Android View Model包含应用程序上下文(以检索上下文调用getApplication()),而我们需要用SharedPreference,所以Android View Model是最简便的。
My View Model:
package com.example.androidviewmodel; import android.app.Application; import android.content.Context; import android.content.SharedPreferences; import androidx.annotation.NonNull; import androidx.lifecycle.AndroidViewModel; import androidx.lifecycle.LiveData; import androidx.lifecycle.SavedStateHandle; public class MyViewModel extends AndroidViewModel { private SavedStateHandle handle; private String key = getApplication().getResources().getString(R.string.DATA_KEY); private String shp_name = 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(){ // 以LiveData<Integer>返回key return handle.getLiveData(key); } // 读取 public void load(){ SharedPreferences shp = getApplication().getSharedPreferences(shp_name, Context.MODE_PRIVATE); // 去处key值,如果key值不存在,则赋值为0. int x = shp.getInt(key,0); // 将key值存入handle handle.set(key,x); } // 存储 public void save(){ SharedPreferences shp = getApplication().getSharedPreferences(shp_name, 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()+x); } }
Activity:
package com.example.androidviewmodel; import androidx.appcompat.app.AppCompatActivity; import androidx.databinding.DataBindingUtil; import androidx.lifecycle.SavedStateViewModelFactory; import androidx.lifecycle.ViewModelProvider; import androidx.lifecycle.ViewModelProviders; import android.os.Bundle; import com.example.androidviewmodel.databinding.ActivityMainBinding; 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 SavedStateViewModelFactory(getApplication(),this)).get(MyViewModel.class); binding.setData(myViewModel); binding.setLifecycleOwner(this); } @Override protected void onPause() { super.onPause(); myViewModel.save(); } }
对于save()方法的存放,可以放在数据修改里,即add()方法里,但是如果数据经常变化,那么会消耗很多时间。不要放在 onStop和onDestory里,因为它们都有可能被跳过,比如系统杀死时不会跳过onDestory。
运行结果:
重启或退出都不会导致数据丢失。