2016-02-26 76 views
-3

我有两个应用程序,App1和App2。我想使用App2中的共享偏好和访问将数据保存在App1中,反之亦然。 我可以在App1中保存数据并在App2中访问,但不是相反。如何使用共享首选项在两个Android应用程序之间共享数据?

这是我现在在做什么:

在清单:

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

在应用1:

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

在应用2:

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

最好使用'ContentProvider'了点。这是最好的 –

+0

http://developer.android.com/guide/topics/providers/content-provider-creating.html –

+0

我只需要分享一些字符串。为此,最好使用ContentProvider? – Pratik

回答

0

用户CONTEXT_IGNORE_SECURITY和MODE_WORLD_WRITEABLE两个应用程序

之间共享数据
1

当edit.apply(将数据写入到共享偏爱使用)代替edit.commit(),如将edit.apply即时更新偏好对象并将异步保存新值,以便读取最新值。

使用此代码:

在清单:

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

在应用1:

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

在应用2:

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