Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

two service with the same intent filter

Tags:

android

I have two applications installed on my device,each with a service component in it and these two service has the same intent filter declaration,like this:

<intent-filter>
<action android:name="com.example.intent.action.SHOW"/>
</intent-filter>

And I start the service in this way:

Intent intent = new Intent();
intent.setAction("com.example.intent.action.SHOW");
startService(intent);

I found that one of these two services started,but I am not sure how this happened.As we know,if we write two activities with the same intent filter declaration,a dialog will be poped up and let the user chooses a activity to complete the action.What got me confused is that how Android chooses the service to be started in these who has the same intent filters,what's the strategy of making this decision?

Thanks in advance!

update:
Yury is right, here is code snippet from frameworks/base/services/java/com/android/server/pm/PackageMangerService.java on ICS:

public ResolveInfo resolveService(Intent intent, String resolvedType,
    int flags) {
List<ResolveInfo> query = queryIntentServices(intent, resolvedType,
        flags);
if (query != null) {
    if (query.size() >= 1) {
        // If there is more than one service with the same priority,
        // just arbitrarily pick the first one.
        return query.get(0);
    }
}
return null;
}

As we can see,if there are more than one service match the requested intent, Android will arbitrarily pick one to start. But, which service will be actually started is unexpected.

like image 391
CalvinLee Avatar asked Dec 05 '11 05:12

CalvinLee


2 Answers

If there are more than 1 Service with the same intent-filter then Android OS randomly selects one of these Services and pass to it the intent.

like image 118
Yury Avatar answered Nov 15 '22 13:11

Yury


If there are more than 1 Service with matching IntentFilter the one with highest priority will be picked. If there are multiple Services that have highest priority - than a "random" Service will be picked.

Here is the piece of code that insures that first item has highest priority:

https://github.com/aosp-mirror/platform_frameworks_base/blob/ics-mr0-release/services/java/com/android/server/IntentResolver.java

like image 32
inazaruk Avatar answered Nov 15 '22 15:11

inazaruk