【发布时间】:2018-11-08 13:00:46
【问题描述】:
出于某种原因,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)) 但你正在读取它之外的值 -
你确定它执行了应该保存它的代码吗?你试过调试吗?
-
我相信它会执行
标签: android multithreading save sharedpreferences