具有相同意图过滤器的两个服务

Cal*_*Lee 13 android

我的设备上安装了两个应用程序,每个应用程序都有一个服务组件,这两个服务具有相同的intent过滤器声明,如下所示:

<intent-filter>
<action android:name="com.example.intent.action.SHOW"/>
</intent-filter>
Run Code Online (Sandbox Code Playgroud)

我以这种方式启动服务:

Intent intent = new Intent();
intent.setAction("com.example.intent.action.SHOW");
startService(intent);
Run Code Online (Sandbox Code Playgroud)

我发现这两个服务中的一个已启动,但我不确定这是如何发生的.如我们所知,如果我们使用相同的intent过滤器声明编写两个活动,则会启动一个对话框并让用户选择一个活动来完成让我感到困惑的是,Android如何选择在具有相同意图过滤器的人中启动服务,做出此决定的策略是什么?

提前致谢!

更新:
Yury是对的,这里是来自ICS上的frameworks/base/services/java/com/android/server/pm/PackageMangerService.java的代码片段:

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;
}
Run Code Online (Sandbox Code Playgroud)

我们可以看到,如果有多个服务匹配请求的意图,Android会随意选择一个启动.但是,实际启动的服务是出乎意料的.

Yur*_*ury 11

如果有多个具有相同intent-filter的Service,则Android OS会随机选择其中一个Services并将其传递给intent.


ina*_*ruk 5

如果有超过 1 个服务与匹配的 IntentFilter 匹配,则将选择优先级最高的服务。如果有多个具有最高优先级的服务 - 则将选择“随机”服务。

这是确保第一项具有最高优先级的代码段:

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