【发布时间】:2017-08-22 07:04:28
【问题描述】:
如果我在内部修改默认 sharedPreferences 文件,SharedPreferences 值不会出现。但是,如果我正在关闭和打开应用程序,那么它会很好。
由于某些要求,我将 sharedPreferences 文件存储在谷歌驱动器中。之后,我使用相同的谷歌帐户在其他设备中恢复相同的 sharedPreferences 数据,所有 xml 数据都很好。但在 sharedPreferences 对象中,这些值不会刷新。但是,虽然关闭和打开应用程序值会很好。
如何在不关闭应用程序的情况下刷新 sharedPreferences?
以下是我在默认文件路径强文本中编写 sharedPreferences 文件的方法。
private void restore(Context ctx, InputStream myInputs, String path) {
OutputStream myOutput;
try {
myOutput = new FileOutputStream(path);
byte[] buffer = new byte[1024];
int length;
while ((length = myInputs.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
// Close and clear the streams
myOutput.flush();
myOutput.close();
myInputs.close();
googleDriveBackUpActivity.setBackUpInfo();
Toast.makeText(ctx, R.string.successfully_restored_from_google_drive, Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
}
【问题讨论】:
-
我很确定
SharedPreferences在第一次加载后会缓存,这样它就不需要一直打到磁盘上。与其直接写入 xml 文件,不如使用SharedPreferences.Editor,以便 Android 知道何时使缓存无效。
标签: java android sharedpreferences google-drive-android-api