How can I share data between Two Android Apps using Shared Preferences?

非 Y 不嫁゛ 提交于 2019-12-20 07:48:57

问题


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.

This is what I'm doing now :

In Manifest:

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

In App1:

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

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

Guys any clue ?


回答1:


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.

Use this code:

In Manifest:

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

In App1:

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

In 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:


user CONTEXT_IGNORE_SECURITY and MODE_WORLD_WRITEABLE for access shared data between two apps



来源:https://stackoverflow.com/questions/35652147/how-can-i-share-data-between-two-android-apps-using-shared-preferences

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!