Search code examples
javaandroidandroid-intentservice

Starting service from another app with intent-filter


Until a month ago I was successfully starting the service from another app of mine using intent-filter.

App A:

 <service
            android:name="com.example.app.MyService"
            android:enabled="true"
            android:exported="true" >
            <intent-filter>
                <action android:name="com.test.START" />
            </intent-filter>
</service>

App B:

public static Intent createExplicitIntent(Context context, Intent intent) {
    List<ResolveInfo> queryIntentServices = context.getPackageManager().queryIntentServices(intent, 0);
    System.out.println(queryIntentServices.size());

    if (queryIntentServices.size() != 1) {
        return null;
    }

    ResolveInfo resolveInfo = queryIntentServices.get(0);
    ComponentName componentName = new ComponentName(resolveInfo.serviceInfo.packageName, resolveInfo.serviceInfo.name);
    Intent intent2 = new Intent(intent);
    intent2.setComponent(componentName);
    return intent2;
}

And then finally:

 Intent intent = new Intent("com.test.START");
 createExplicitIntent(context, intent);

But for some reason it stopped working. Not sure what I've changed that broke this approach.


Solution

  • You need a <queries> element in App B if you want your code to work on Android 11 and higher, as you need to declare your package visibility needs.

    In your case, something like this might work:

        <queries>
            <intent>
                <action android:name="com.test.START" />
            </intent>
        </queries>