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:

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=""
Get Context from other package:
mContext = context.createPackageContext(
 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",
            SharedPreferences.Editor editor = prefs.edit();
            editor.putString("demostring", strShareValue);
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");

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

No comments:

Post a comment