如何使用共享首选项在两个Android应用程序之间共享数据?

时间:2016-02-26 12:47:46

标签: android sharedpreferences

我有两个应用程序,App1和App2。我想在App1中使用共享首选项和App2中的访问来保存数据,反之亦然。 我能够在App1中保存数据并在App2中访问,但不能相反。

这就是我现在正在做的事情:

在清单中:

android:sharedUserId="any string"
android:sharedUserLabel="@string/any_string"

在App1中:

SharedPreferences prefs = getSharedPreferences("demopref",Context.MODE_PRIVATE);
SharedPreferences.Editor editor =prefs.edit();
editor.putString("demostring", strShareValue);
editor.commit();

在App2中:

try {
con = createPackageContext("com.sharedpref1", 0);
SharedPreferences pref = con.getSharedPreferences("demopref", Context.MODE_PRIVATE);
String your_data =
pref.getString("demostring", "No Value");
}
catch (NameNotFoundException e) {
Log.e("Not data shared", e.toString());
}

伙计们有什么线索?

2 个答案:

答案 0 :(得分:1)

将数据写入共享首选项时,使用edit.apply()而不是edit.commit(),因为edit.apply会立即更新首选项对象并异步保存新值,因此允许您读取最新值

使用此代码:

在清单中:

android:sharedUserId="any string"
android:sharedUserLabel="@string/any_string"

在App1中:

SharedPreferences prefs = getSharedPreferences("demopref",Context.MODE_PRIVATE);
SharedPreferences.Editor editor =prefs.edit();
editor.putString("demostring", strShareValue);
editor.apply();

在App2中:

try { 
con = createPackageContext("com.sharedpref1", 0);
SharedPreferences pref = con.getSharedPreferences("demopref", Context.MODE_PRIVATE);
String your_data =
pref.getString("demostring", "No Value");
} 
catch (NameNotFoundException e) {
Log.e("Not data shared", e.toString());
} 

答案 1 :(得分:0)

用户CONTEXT_IGNORE_SECURITY和MODE_WORLD_WRITEABLE,用于访问两个应用之间的共享数据

相关问题