Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - Share resource between two applications

Tags:

android

I have two applications, one works as a main app, and the another as a service. In the service app manifest file, I configure a service like:

<service android:name=".services.FirstService">
    <intent-filter>
        <action android:name="ch.service.action.FIRST_SERVICE"/>
    </intent-filter>
</service>

And in the main app, I start a service like:

Intent intent = new Intent("ch.service.action.FIRST_SERVICE");
startService(intent);

Here, I have to duplicate "ch.service.action.FIRST_SERVICE". How can I avoid this? How can I share some common constants, for example define one in service app, and can be retrieve in main app?

Any answer is appreciated.

like image 302
Hong Nguyen Avatar asked Nov 09 '22 05:11

Hong Nguyen


1 Answers

You should use SharedPreference between both of your application. In your Service application you should write the String ch.service.action.FIRST_SERVICE to SharedPreference :

SharedPreference sharedPreferences = getSharedPreferences("any_name", Context.MODE_WORLD_READABLE);
SharedPreference.Editor mEditor = sharedPreferences.edit();
mEditor.putString("service_string","ch.service.action.FIRST_SERVICE");
mEditor.commit();

When you want to get the value from other application, you first need to get Context of your service application :

Context mServiceAppContext = createPackageContext("com.example.service_app_package", 0);

You can use mServiceAppContext to get the String value :

SharedPreference sharedPreferences = mServiceAppContext.getSharedPreferences("any_name", Context.MODE_WORLD_READABLE);    
// Context.MODE_WORLD_READABLE is important, it makes the value readable across other applications

sharedPreferences.getString("service_string", /* default value */ "service_string","ch.service.action.FIRST_SERVICE");

Best Explaination is given at : http://thedevelopersinfo.com/2009/11/25/getting-sharedpreferences-from-other-application-in-android/

like image 185
Kushal Avatar answered Nov 14 '22 23:11

Kushal