Monday, 2 November 2015

share data between two apps

There are many different ways to share data between two apps.

AIDL is an option.

serviceboradcast is another

you can use them in different cases.


this blog will explain you how to use share preference to share data(settings) between apps. You can use this solution for sharing settings data (e.g. current store id...)



Very important: these apps should be signed by same certificates



Very easy:

http://stackoverflow.com/questions/11025234/how-can-i-share-a-sharedpreferences-file-across-two-different-android-apps





It is better to set private mode for the file. App needs to be signed with same set of certificates to share this file.
Set sharedUserId in both apps to be same.
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.hello"
android:versionCode="1"
android:versionName="1.0" 
android:sharedUserId="com.example">
....
Get Context from other package:
mContext = context.createPackageContext(
                        "com.example.otherapp",
                        Context.MODE_PRIVATE);
 mPrefs = mContext.getSharedPreferences("sameFileNameHere", Activity.MODE_PRIVATE);
Get items as usual from SharedPreference. You can access it now.

but sharedUserId is not nessary.




This is a good example as well:


Okay! using this code in Application 1 ( with package name is "com.sharedpref1" ) to store data with Shared Preferences.
SharedPreferences prefs = getSharedPreferences("demopref",
                    Context.MODE_WORLD_READABLE);
            SharedPreferences.Editor editor = prefs.edit();
            editor.putString("demostring", strShareValue);
            editor.commit();
And using this code in Application 2 to get data from Shared Preferences in Application 1. We can get it because we use MODE_WORLD_READABLE in application 1:
    try {
                con = createPackageContext("com.sharedpref1", 0);
                SharedPreferences pref = con.getSharedPreferences(
                        "demopref", Context.MODE_PRIVATE);
                String data = pref.getString("demostring", "No Value");
                displaySharedValue.setText(data);

            } catch (NameNotFoundException e) {
                Log.e("Not data shared", e.toString());
            }








No comments:

Post a comment