服务清单中的 intent-filter 有什么用?

What is the use of intent-filter in the manifest for a service?

我在火车上,突然想到一件事

如果允许我如下声明我的服务:

<service
    android:name=".service.MyService"
    android:enabled="true"
    android:exported="true">
    <intent-filter>
        <action android:name="INTENT_SAMPLE" />
        <category android:name="android.intent.category.DEFAULT" />
        <data android:mimeType="text/plain" />
    </intent-filter>
</service>

我知道执行以下操作会导致 IllegalArgumentException: Service Intent must be explicit 错误。

Intent intent = new Intent("INTENT_SAMPLE");
intent.setType("text/plain");
startService(intent);

那么,如果有的话,intent-filter在这种情况下有什么用呢?

如果您想使用服务执行不同的操作,那么声明一个意图过滤器将帮助您的服务匹配您要执行的不同操作。

它允许您对不同的操作使用相同的服务,而不是创建两个单独的服务。

但是,为服务声明意图过滤器并不是一个好的做法,这就是文档不得不说的:

Caution: To ensure your app is secure, always use an explicit intent when starting a Service and do not declare intent filters for your services. Using an implicit intent to start a service is a security hazard because you cannot be certain what service will respond to the intent and the user cannot see which service starts.

我在 SO 上找到了很多关于相同问题的答案:

希望你明白了。

谢谢。

意图的定义是 Intent 是一个简单的消息对象,用于在 android 组件(例如活动、内容提供者、广播接收器和服务)之间进行通信。意图还用于在活动之间传输数据。

并且有两种类型的意图 隐含意图 明确的意图

隐式意图是使用两个定义您要为不同活动执行的操作

Explicit Intent 用于启动特定的应用程序组件,例如应用程序中的特定 activity 或服务

这就是为什么您必须在清单中的 intent-filter 中定义意图,以便系统知道它是哪种类型的意图

您可以参考此链接以进一步详细了解该主题:- https://developer.android.com/guide/components/intents-filters https://developer.android.com/guide/topics/manifest/intent-filter-element

   try this code....
   <code>
    //MainActivity.class
    Intent serviceIntent = new Intent(context,MyService.class);
    serviceIntent.setAction("INTENT_SAMPLE");
    startService(serviceIntent);

  // Myservice.class
  public int onStartCommand(Intent intent, int flags, int startId) 
  {
      string action=intent.getAction();
      if(action.equals("your action"))
      {...}
  }
  </code>

如其他答案中所述,意图过滤器可帮助您的服务class确定要执行的操作类型。因此,例如,您可以尝试像下面这样启动服务:

Intent intent = new Intent(this, MyService.class);
intent.setAction("INTENT_SAMPLE");
startService(intent);

然后在 MyService class 中,像这样检查操作:

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    if("INTENT_SAMPLE".equals(intent.getAction())) {
        // do INTENT_SAMPLE action here
    }
    else {
        // do non INTENT_SAMPLE action here
    }
}

由于 https://developer.android.com/guide/components/intents-filters#Types 不推荐服务的意图过滤器,因此从清单中删除该操作。要获得与上述相同的结果,只需像这样在您的意图中添加额外的内容:

Intent intent = new Intent(this, MyService.class);
intent.putExtra("INTENT_SAMPLE", true);
startService(intent);

然后在 MyService class 中,像这样检查操作:

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    if(intent.getBooleanExtra("INTENT_SAMPLE", false)) {
        // do INTENT_SAMPLE action here
    }
    else {
        // do non INTENT_SAMPLE action here
    }
}

干杯!