2016-02-26 40 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()); 
} 
相關問題