Data sharing between two applications

Send data from Application 1 (for ex:Application 1 package name is "com.sharedpref1" ).

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

Receive the data in Application 2( to get data from Shared Preferences in Application 1).

    try {
            con = createPackageContext("com.sharedpref1", 0);//first app package name is "com.sharedpref1"
            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());
         }

In both application manifest files add same shared user id & label,

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

both are same... and shared user label must from string.xml

like this example.

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.xxxx"
android:versionCode="1"
android:versionName="1.0"
android:sharedUserId="any string" 
android:sharedUserLabel="@string/any_string">

If you want to share data between applications, make sure you sign with the same key:

Code/data sharing through permissions – The Android system provides signature-based permissions enforcement, so that an application can expose functionality to another application that is signed with a specified certificate. By signing multiple applications with the same certificate and using signature-based permissions checks, your applications can share code and data in a secure manner.

This is quoted from: android developer page about signing

If it's a small amount of data you could send it through an intent.


ContentProviders are a good approach to share data between applications.


I suspect they were likely looking for Android specific methods such as the content provider answer.

Other alternatives... Android Specific - Remote services General - TCP/IP connections General - Writing to a location on the SD card

Care to hear more about a specific method?

Also stealing this question for an interview today :)

Tags:

Android