通过 BroadcastReceiver 启动 Service 或 IntentService 有什么意义?

What is the point to start the Service or IntentService via BroadcastReceiver?

我见过一些 Google 代码实现,其中服务或 IntentServices 通过 BroadcastReceiver 启动。我不明白这是否有技术原因? 唯一停止启动服务的代码是检查 ContentProvider 是否为 null。

if(provider == null) {
   // the provider is not initialised, yet...
   return;
}

p.s。我怀疑的一件事是性能,当服务启动比 BroadcastReceiver 贵一点时,但我不确定这就是为什么我想听听一些专家对此的意见 :) 只是想了解何时执行此操作,何时不执行此操作。

您可以让 android 系统通过 IntentFilters 触发 BroadcastReceiver 的 onReceive

例如,如果您对用户更改其设备的蓝牙设置感兴趣,您可以这样做

<receiver android:name=".BTSettingsChangedReceiver">
    <intent-filter>
        <action android:name="android.bluetooth.adapter.action.STATE_CHANGED" />
    </intent-filter>
</receiver>

当发生这种情况时系统会自动调用BroadcastReceiver

这不是您 can/should 使用服务或 IntentService* 做的事情。因此,您使用 BroadcastReceiver 在接收器的 onReceive.

中通过 context.startService() 手动启动它

*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.

BroadcastReceivers 是您应用中的侦听器。你让它们监听事件,当事件被触发时,它们会告诉其他组件继续。

通常你将 BroadcastReceivers 与 Services 结合起来,这样第一个可以被不同的事件触发多次,后者知道什么时候做或不做(例如,根据事件多次广播启动服务,但因为服务已经在处理一些东西,它只是忽略进一步的调用,直到它完成)。也可以堆砌intents,不过就是这个意思,目的不一样