android - 用于连续存储数据的 Android 共享首选项
问题描述
我正在学习安卓。我对共享首选项文件有疑问。
我创建了一个前台服务。服务递增计数变量,该变量初始化为 0。
每当服务被销毁并重新启动时,count 变量就会再次从 0 开始。但是,我想从以前的值开始。所以,我必须将它存储在本地。
这是 onStartCommand() 方法。
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
startForeground(NOTIFICATION_ID, displayNotification());
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
//I have to store this count value
count++;
sharedPrefEditor.putInt("COUNT_NUMBER", count);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
thread.start();
return START_STICKY;
}
我将计数值存储在共享首选项文件中。
在这种情况下,共享偏好是最好的吗?还是有更好的方法来做到这一点?
我可以将计数变量设为静态并将其值存储在 onDestroy() 方法的共享首选项文件中,但不能保证调用 onDestroy()。
我的要求是我必须在服务被销毁时存储计数值。这个怎么做?
解决方案
推荐阅读
- java - 关于返回参数的java mapper ibatis错误
- xamarin.android - 为什么 Xamarin Android 中的 BiometricPrompt API 不包含 onAuthenticationError 回调
- css - 不考虑大小的媒体查询
- javascript - PDF.JS with CANVAS Draw : 在画布中绘制矩形,使用 pdf.js 加载 PDF
- c# - ajax调用后如何停止刷新页面(仅在保存图像时发生)?
- html - HTML 永久激活悬停和活动状态
- c# - 为什么站点显示一个页面只能有一个服务器端Form标签
- kubernetes - Prometheus 查询仅获取处于运行状态的 Pod 的 CPU 和内存请求
- python - 执行动态循环(来自变量)来创建气流任务是一种好方法吗?
- firebase - 动作必须是普通对象。为异步操作、firebase、redux、redux-thunk 使用自定义中间件