android - SharedPreferences 不保存值
问题描述
由于某种原因 SharedPreferences 不保存值,代码在服务中......
Thread thread = new Thread() {
public void run() {
SharedPreferences sharedPref = getBaseContext().getSharedPreferences(getString(R.string.not_local_sp), MODE_PRIVATE);
long lastExecuted = sharedPref.getLong(getString(R.string.timeDone), 0L);
int scanInterval = 500 * 60 * 60;
while (true) {
if (System.currentTimeMillis() - lastExecuted >= scanInterval && contextCreator == null) {
Log.d(TAG, "inside while loop");
Log.d(TAG, String.valueOf(System.currentTimeMillis() - lastExecuted));
Log.d(TAG, String.valueOf(lastExecuted));
Log.d(TAG, String.valueOf(scanInterval));
contextCreator = new ProtectionContextCreator();
feature = AppScanFactory.createAppScan(getBaseContext());
feature.add(new BoostFeature(getBaseContext(), new StubScanStore()));
contextCreator.create(getBaseContext(), feature.getType(), NotificationService.this);
/*Shared pref*/
SharedPreferences.Editor editor = sharedPref.edit();
editor.putLong(getString(R.string.timeDone), System.currentTimeMillis());
editor.commit();
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
thread.start();
lastExecuted 变量始终获得默认值 0。
解决方案
您有一个无限循环 ( while(true)
) 但您正在读取它之外的值
这条线
long lastExecuted = sharedPref.getLong(getString(R.string.timeDone), 0L)
应该在 while 循环内(如果您lastExecuted
用于检查值是否已存储)
推荐阅读
- d3.js - 在d3中制作轴刻度字符串
- django - 如何在 Django 中获取重定向函数的输出?
- c# - 如何以编程方式获取当前 nuget 包的版本?
- django - Postgres TIME 与 TIME 与时区
- r - 让 facet_grid 中的每个图都有自己的 Y 轴值
- ios - 如何同步 UICollectionViewCell 内的 UITableView 之间的滚动(在 UICollectionViewController 内)
- javascript - 在 Gutenberg 自定义横幅块中使用页面标题
- url - CMIS 的 URL 字符串构造
- php - 使用 $_GET 后变量和字符串不会回显
- r - RPostgreSQL - 根据主键向量查询表的主键