Reputation: 1488
I have seen some Google code implementations where the Services or IntentServices are started through BroadcastReceiver. I can't understand is there a technical reason for this or not? The only code which stops to start the service is the check whether the ContentProvider is null or not.
if(provider == null) {
// the provider is not initialised, yet...
return;
}
p.s. One thing which I doubt is the performance, when the service start is a bit more expensive, than the BroadcastReceiver, but I am not sure that's why I would like to hear some experts opinion about this :) Just want to understand when to do this and when not.
Upvotes: 0
Views: 144
Reputation: 506
BroadcastReceivers are listeners in your app. You have them listening to events, when triggered, they tell other components to proceed.
Usually you combine BroadcastReceivers with Services so the first can get triggered multiple times by different events, the later knows when to do stuff or not (e.g. broadcast start service multiple times based on events, but as the service is already processing something, it just ignore further calls till it is done). It can also pile up intents, but that's the idea, they have different purposes.
Upvotes: 1
Reputation: 43314
You can let the android system trigger a BroadcastReceiver's onReceive
through IntentFilters.
For example if you are interested in users changing their device's bluetooth setting, you can do
<receiver android:name=".BTSettingsChangedReceiver">
<intent-filter>
<action android:name="android.bluetooth.adapter.action.STATE_CHANGED" />
</intent-filter>
</receiver>
and the system will automatically call the BroadcastReceiver when it happens.
This is not something you can/should do with a Service or IntentService*. So you use the BroadcastReceiver to start it manually by context.startService()
in the receiver's onReceive
.
*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.
Upvotes: 2