在服务中为什么不声明意图过滤器?

In Service why not to declare intent filter?

https://developer.android.com 我发现了以下语句。

注意:为避免无意中 运行 不同应用的服务,请始终使用明确的意图来启动您自己的服务,并且不要为您的服务声明意图过滤器。

请告诉我为什么不为我的服务声明 Intent 过滤器?

因为有可能启动属于某个其他应用程序且具有相同 Intent 过滤器的服务。

用户可以在他的设备上安装另一个应用程序(可能不止一个),该应用程序可以提供具有相同意图过滤器的服务。如果您尝试 运行 您的服务发送广播意图,您可能会不小心 运行 此应用程序的服务。

让我尝试重述上面的句子以阐明其含义:

Caution: To avoid inadvertently running a different app's Service, always use an explicit intent to start your own service...

当您广播隐式 意图时,Android 会检查哪些应用程序已注册接收此意图。多个应用程序可以注册到同一个 Intent,在这种情况下,如果您的意图是仅启动您自己的服务,而另一个服务注册到同一个 Intent Action,Android 可能会启动另一个服务而忽略您的服务。

always use an explicit intent to start your own service and do not declare intent filters for your service.

为了避免上述情况,Android 允许使用明确的 Intent 启动您的服务。在您的显式 Intent 中,您提供了需要启动的确切包名和服务 class。这允许 Android 精确定位您的服务并启动它,而不会将其与设备上可能安装的其他服务混淆。此外,当使用显式 Intent 时,您不需要为该 Intent 注册 Intent 过滤器,因为 Android 确切地知道要做什么以及启动哪个服务,因为所有需要的信息都封装在 Intent 中。

这是一个明确意图的例子:

Intent downloadIntent = new Intent(this, DownloadService.class);
downloadIntent.setData(Uri.parse(fileUrl));
startService(downloadIntent);

创建 Intent 时,您通过将 "this" 作为参数传递来提供应用程序(进程)的上下文。此外,您传递服务的确切 class 名称 (DownloadService.class)。现在,Android 确切地知道启动哪个服务,不会与多个选择混淆。