【问题标题】:How can I share data between Two Android Apps using Shared Preferences?如何使用共享首选项在两个 Android 应用程序之间共享数据?
【发布时间】:2016-03-04 15:26:18
【问题描述】:

我有两个应用程序,App1 和 App2。我想在 App2 中使用共享首选项和访问权限将数据保存在 App1 中,反之亦然。 我可以在 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());
}

各位有什么线索吗?

【问题讨论】:

标签: android sharedpreferences


【解决方案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());
} 

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多