Reputation: 53
On https://developer.android.com i found following statement.
Caution: To avoid inadvertently running a different app's Service, always use an explicit intent to start your own service and do not declare intent filters for your service.
Please tell me why not to declare intent filter for my service?
Upvotes: 3
Views: 687
Reputation: 813
Let me try to refrace the above sentence to clerify what it means:
Caution: To avoid inadvertently running a different app's Service, always use an explicit intent to start your own service...
When you broadcast an implicit intent, Android checks which applications are registered to receive this Intent. Multiple applications can register to the same Intent, In that case, if your intention was to launch only your own service and another service is registered to the same Intent Action, Android might start the other Service and ignore yours.
always use an explicit intent to start your own service and do not declare intent filters for your service.
To avoid the scenario mentioned above, Android allows to start your service with an explicit Intent. In your explicit Intent, you provide the exact package name and Service class that needs to be initiated. This allows Android to pinpoint your Service and start it without confusing it with other Services that might be installed on the device. Moreover, when using an explicit Intent, you don't need to register an Intent filter for that Intent because Android knows exactly what to do and which Service to start as all the needed information is encapsulated inside the Intent.
Here is an example of an explicit intent:
Intent downloadIntent = new Intent(this, DownloadService.class);
downloadIntent.setData(Uri.parse(fileUrl));
startService(downloadIntent);
When you create the Intent you provide the Context of your application (process) by passing "this" as an argument. In addition, you pass the exact class name (DownloadService.class) of your Service. Now, Android knows exactly which Service to start and will not be confused with multiple choices.
Upvotes: 1
Reputation: 31
Because there is a probability to launch service that belongs to some other application and has the same intent filter.
User can have another app (probably more than one) on his device, that can has service with the same intent filter. If you send broadcasting intent trying to run your service, you can accidently run the service of this app.
Upvotes: 0