我的设备上安装了两个应用程序,每个应用程序都包含一个服务组件,这两个服务具有相同的intent过滤器声明,如下所示:
<intent-filter>
<action android:name="com.example.intent.action.SHOW"/>
</intent-filter>
我以这种方式启动服务:
Intent intent = new Intent();
intent.setAction("com.example.intent.action.SHOW");
startService(intent);
我发现这两个服务中的一个已启动,但我不确定这是怎么发生的。如我们所知,如果我们使用相同的intent filter声明编写两个活动,则会启动一个对话框并让用户选择一个完成动作的活动。让我感到困惑的是,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;
}
正如我们所看到的,如果有多个服务符合所请求的意图,Android将随意选择一个启动。但是,实际启动哪种服务是出乎意料的。
答案 0 :(得分:10)
如果有多个Service使用相同的intent-filter,那么Android OS会随机选择其中一个服务并将其传递给它。
答案 1 :(得分:4)
如果有多个具有匹配的IntentFilter的服务,则将选择具有最高优先级的服务。如果有多个服务具有最高优先级 - 那么将选择“随机”服务。
以下是确保第一项具有最高优先级的代码: