Skip to content Skip to sidebar Skip to footer

How To Start Android Service From Another Android App

I'm having a problem starting a service from another Android app (API 17). However, if I do run 'am' from the shell, the service starts fine. # am startservice com.xxx.yyy/.SyncSer

Solution 1:

You should be able to start your service like this:

Intent i = new Intent();
i.setComponent(new ComponentName("com.xxx.yyy", "com.xxx.yyy.SyncService"));
ComponentName c = ctx.startService(i);

You don't need to set ACTION or CATEGORY if you are specifying a specific component. Make sure that your service is properly defined in the manifest.


Solution 2:

Start your service like this

Intent intent = new Intent();
intent.setComponent(new ComponentName("pkg", "cls"));
ComponentName c = getApplicationContext().startForegroundService(intent);

btw you actually need to use the applicationId, instead of the pkg. it can be found in the app gradle. I was struggling with that mistake for hours!

   defaultConfig {
        applicationId "com.xxx.zzz"
}

the cls is the name of your service declared in the manifest. example: com.xxx.yyy.yourService.

 <service android:name="com.xxx.yyy.yourService"
android:exported="true"/>

Solution 3:

As an addition to David Wasser's answer to make it work when targeting API 30 and above you also have to add either:

Required package name in queries tag in manifest:

<queries>
        <package android:name="com.example.service.owner.app" />
</queries>

or permission

<uses-permission android:name="android.permission.QUERY_ALL_PACKAGES" />

Additional info on package visibility changes here


Post a Comment for "How To Start Android Service From Another Android App"