[英]iOS UserDefaults Sharing Preferences Across Multiple Applications Android Equivalent
對於我們的 iOS 應用程序,我們可以讓用戶輸入簡單的鍵值首選項,這些首選項應該保留在同一應用程序組內的 6 個其他應用程序中。 這意味着用戶無需在每次打開其他應用程序時重新輸入這些首選項 6 次。 我們只需調用UserDefaults(suiteName:)
可以做到這一點,它返回一個在所有 7 個 iOS 應用程序中都可讀寫的字典,這非常方便和有用。 是否有與此等效的 Android java? 我們不希望我們所有的 Android 用戶都被迫輸入相同的信息 7 次。 我嘗試創建一個世界可讀/可寫的文件,但似乎無法找到所有 7 個應用程序都可以訪問的適當目錄。
我不得不寫一個 hack 來實現這個功能,這不是首選,但要求是必要的。 我按照Morrison Chang 的建議在此線程中遵循了一些已接受的答案,但最終不得不循環並比較以查看最近更新的首選項文件,然后相應地對運行代碼的應用程序進行更新。
public static SharedPreferences getSharedPreferences(Activity activity) {
SharedPreferences prefs = activity.getApplicationContext().getSharedPreferences(SHARED_PREFS_KEY,
Context.MODE_PRIVATE);
long lastUpdate = prefs.getLong("lastUpdate", 0);
Context packageContext;
for (String app : new String[] { "app1", "app2", "app3", "app4", "app5", "app6" }) {
try {
packageContext = activity.createPackageContext(SHARED_PREFS_KEY + "." + app, 0);
SharedPreferences sharedPrefs = packageContext.getSharedPreferences(SHARED_PREFS_KEY, Context.MODE_PRIVATE);
long sharedLastUpdate = sharedPrefs.getLong("lastUpdate", 0);
if (sharedPrefs != null && sharedLastUpdate > lastUpdate) {
SharedPreferences.Editor editor = prefs.edit();
editor.clear();
for (Map.Entry<String, ?> entry : sharedPrefs.getAll().entrySet()) {
if (entry.getValue() instanceof Boolean)
editor.putBoolean(entry.getKey(), (Boolean) entry.getValue());
else if (entry.getValue() instanceof Float)
editor.putFloat(entry.getKey(), (Float) entry.getValue());
else if (entry.getValue() instanceof Integer)
editor.putInt(entry.getKey(), (Integer) entry.getValue());
else if (entry.getValue() instanceof Long)
editor.putLong(entry.getKey(), (Long) entry.getValue());
else if (entry.getValue() instanceof String)
editor.putString(entry.getKey(), (String) entry.getValue());
}
editor.commit();
break;
}
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
}
return prefs;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.