【问题标题】:two service with the same intent filter具有相同意图过滤器的两个服务
【发布时间】:2012-01-12 22:59:20
【问题描述】:

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

<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);

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

提前致谢!

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

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 将任意选择一个启动。但是,实际上会启动哪个服务是意料之外的。

【问题讨论】:

  • 你自己试试吧。创建项目,形成两个相同意图的服务。你会自动看到会发生什么。所以试试吧兄弟

标签: android


【解决方案1】:

如果有超过 1 个服务具有相同的意图过滤器,则 Android 操作系统会随机选择其中一个服务并将意图传递给它。

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2017-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多