十年网站开发经验 + 多家企业客户 + 靠谱的建站团队
量身定制 + 运营维护+专业推广+无忧售后,网站问题一站解决
小编给大家分享一下Android如何实现关机后数据不会丢失问题,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!
成都创新互联公司坚持“要么做到,要么别承诺”的工作理念,服务领域包括:成都网站设计、成都做网站、外贸网站建设、企业官网、英文网站、手机端网站、网站推广等服务,满足客户于互联网时代的景东网站设计、移动媒体设计的需求,帮助企业找到有效的互联网解决方案。努力成为您成熟可靠的网络建设合作伙伴!
要实现关机后数据也不会丢失,需要使用到 AndroidViewModel,SaveStateHandle 和 SharePreferences 要达到的目的就是将数据保存成这个亚子

就不会出现app在异常闪退或者关机后数据的丢失了注意在使用SaveStateHandle和binding的时候需要在gradle里面设置一波

数据类
package com.example.applicationtest04;
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.MutableLiveData;
import androidx.lifecycle.SavedStateHandle;
public class MyVIewModel extends AndroidViewModel {
SavedStateHandle handle; //声明savedstatehandle 类型
String shpName = getApplication().getResources().getString(R.string.shp_name);
String key = getApplication().getResources().getString(R.string.key);
public MyVIewModel(@NonNull Application application, SavedStateHandle handle) {
super(application);
this.handle = handle;
if(!handle.contains(key)){
load();
}
}
public LiveData 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()+x);
}
}
//这段代码里面有几个重要的点就是在使用handle的时候要注意使用的数据是liveData Mainactive类
package com.example.applicationtest04;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.SavedStateVMFactory;
import androidx.lifecycle.ViewModelProvider;
import androidx.lifecycle.ViewModelProviders;
import android.os.Bundle;
import com.example.applicationtest04.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);
this.myVIewModel = ViewModelProviders.of(this,new SavedStateVMFactory(this)).get(MyVIewModel.class);
binding.setData(myVIewModel);
binding.setLifecycleOwner(this);
}
@Override
protected void onPause() {
super.onPause();
myVIewModel.save();
}
}
//这段代码的重点就是使用onPause这个声明周期的函数来调用save()函数布局xml
测试效果先加到12

再重启

重启之后重新打开app

值还是没有变化测试成功
以上是“Android如何实现关机后数据不会丢失问题”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注创新互联行业资讯频道!