Wednesday, 2 December 2015

Android: start Service of another app

So you want to start a Service which belongs to another app? There's two ways to do this depending on how the Service has been defined.

Let's assume first that the Service is defined in the manifest of the first app with the exported attribute as follows:

<manifest
    xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.thinkincode.someapp" >
    <application>
        <service
            android:name=".SomeService"
            android:exported="true" />
    </application>
</manifest>

In this case the Service can be started from the second app as follows:

Intent intent = new Intent();
intent.setComponent(new ComponentName(
    "com.thinkincode.someapp",
    "com.thinkincode.someapp.SomeService"));

startService(intent);

The better way of declaring a Service to be used by other apps is of course to use intent filters. So, going back to the manifest of the first app, this is how we'd define the Service:

<manifest
    xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.thinkincode.someapp" >
    <application>
        <service
            android:name=".SomeService"
            android:exported="true">
            <intent-filter>
                <action android:name="StartSomeService" />
            </intent-filter>
        <service/>
    </application>
</manifest>

And this is how we'd now start the Service from the second app:

Intent intent = new Intent();
intent.setAction("StartSomeService");

startService(intent);

That's it! You should now be able to (1) define Services which can be used by other apps and (2) call on Services defined by other apps.

No comments: