【问题标题】:Unable to start intent service via IMPLICIT intent无法通过隐式意图启动意图服务
【发布时间】:2023-03-22 18:53:01
【问题描述】:

AndroidManifest.xml

<application android:name=".MyApplication"
         android:icon="@drawable/icon"
         android:label="@string/app_name"
         >

 <service android:name=".MyService"
          android:exported="true">
          <intent-filter>
            <action android:name="android.service.myapp.MyService.actionA"/>
            <action android:name="android.service.myapp.MyService.actionB"/>
            <category android:name="android.intent.category.DEFAULT"/>
          </intent-filter>

 </service>

</application>

如果我使用以下代码,我的服务就会启动:

Intent intent = new Intent(context, MyService.class);
intent.setAction("android.service.myapp.MyService.actionA");
context.startService(intent);

但是如果我使用以下代码启动它,我的服务不会启动:

Intent intent = new Intent("android.service.myapp.MyService.actionA");
context.startService(intent);

【问题讨论】:

    标签: android android-intent android-service intentservice


    【解决方案1】:

    使用“隐式”Intent 启动或绑定Service 是不安全的。从 Lollipop 开始,bindService() 需要一个显式的 Intent(您的第一个示例,其中为 Service 指定了 ContextClass。)startService() 的行为对于使用的隐式 Intents 是未定义的启动服务。来自startService() 上的文档:

    Intent 应该包含要启动的特定服务实现的完整类名称或要定位的特定包名称。如果 Intent 的指定较少,它会记录一个关于此的警告,并且它找到和使用的多个匹配服务中的哪一个将是未定义的。

    如果您使用显式形式,您可以从清单中完全删除&lt;intent-filter&gt;:它不是必需的。如果您需要通过Intent 指定服务要完成的某种类型的工作,请考虑在Intent 中使用额外的。

    【讨论】:

      猜你喜欢
      • 2011-03-27
      • 2011-11-07
      • 2018-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-20
      相关资源
      最近更新 更多