2016-07-26 59 views
1

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

回答

2

这是不安全的,以使用一个“隐式” Intent启动或与结合Service。从棒棒糖开始,bindService()需要明确的Intent(您的第一个示例,您为Service指定ContextClass。)对于用于启动服务的隐式Intent s,startService()的行为未定义。从startService()的文档:

Intent应该包含要启动的特定服务实现的完整类名称或要包含的特定程序包名称。如果未指定Intent,则会记录有关此信息的警告,以及它找到并使用的多个匹配服务中的哪一个将是未定义的。

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

相关问题