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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With