我有一个 Activity (A),用于检查我的服务器是否有 APK 更新。调用此函数时,无论是否有更新,我都需要编辑共享首选项,以便应用程序知道跳过或运行实际的更新 Activity (B)。问题 1 是,为什么 Activity (A) 没有编辑共享首选项?问题 2 是,如果正在编辑它们,为什么 Activity (B) 不读取它们?
提前谢谢您!
应在此处编辑共享首选项( Activity (A)):
private void parseJson(String result) {
try {
JSONObject obj = new JSONObject(result);
String updateMessage = obj.getString(Constants.APK_UPDATE_CONTENT);
String apkUrl = obj.getString(Constants.APK_DOWNLOAD_URL);
int apkCode = obj.getInt(Constants.APK_VERSION_CODE);
int versionCode = AppUtils.getVersionCode(mContext);
if (apkCode > versionCode) {
if (mType == Constants.TYPE_NOTIFICATION) {
showNotification(mContext, updateMessage, apkUrl);
} else if (mType == Constants.TYPE_DIALOG) {
SharedPreferences pref = mContext.getSharedPreferences("ActivityUpdatePREF", Context.MODE_PRIVATE);
SharedPreferences.Editor ed = pref.edit();
ed.putBoolean("activity_update", true);
ed.apply();
showDialog(mContext, updateMessage, apkUrl);
}
} else if (mShowProgressDialog) {
SharedPreferences pref = mContext.getSharedPreferences("ActivityUpdatePREF", Context.MODE_PRIVATE);
SharedPreferences.Editor ed = pref.edit();
ed.putBoolean("activity_update", false);
ed.apply();
Toast.makeText(mContext, mContext.getString(R.string.android_auto_update_toast_no_new_update), Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
Log.e(Constants.TAG, "parse json error");
}
}
Activity (B):
SharedPreferences pref = getSharedPreferences("ActivityUpdatePREF", Context.MODE_PRIVATE);
if(pref.getBoolean("activity_update", false)){
Intent intent = new Intent(this, Main.class);
deleteCache(getApplicationContext());
startActivity(intent);
finish();
} else {
functionUp();
}
最佳答案
使用 commit() 而不是 apply()
Unlike commit(), which writes its preferences out to persistent storage synchronously, apply() commits its changes to the in-memory SharedPreferences immediately but starts an asynchronous commit to disk and you won't be notified of any failures. If another editor on this SharedPreferences does a regular commit() while a apply() is still outstanding, the commit() will block until all async commits are completed as well as the commit itself.
https://developer.android.com/reference/android/content/SharedPreferences.Editor.html#apply()
关于java - 共享首选项不应用更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47318472/