我如何共享使用共享preferences两款Android Apps之间的数据? [英] How can I share data between Two Android Apps using Shared Preferences?

查看:135
本文介绍了我如何共享使用共享preferences两款Android Apps之间的数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个应用程序,App1和App2的。我想使用共享preference并获得在App2的,反之亦然在App1的数据保存。
我能够在App1和数据访问保存在App2的,但不是相反。

I have Two Apps, App1 and App2. I want to save data in App1 using shared preference and access in App2 and vice versa. I'm able to save data in App1 and access in App2 but not the opposite.

这是我现在在做什么:

在清单:

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());
}

家伙任何线索?

推荐答案

在edit.apply数据写入共享preference使用()而不是edit.commit(),如edit.apply将更新preference对象,并立即将异步保存新的值,因此让您阅读最新的值。

When writing data to the shared preference use edit.apply() instead of edit.commit(), as edit.apply will update the preference object instantly and will save the new values asynchronously, so allowing you to read the latest values.

使用此code:

在清单:

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());
} 

这篇关于我如何共享使用共享preferences两款Android Apps之间的数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆