I read some similar questions (for example at this link), but the problem I’m asking is a bit different. In fact, in my case the service is started manually by the startService method, then as a consequence it can not be started using the bindService method.
- Suppose we have a package that contains the
MainServiceservice andMainServiceActivityactivity. In the file “AndroidManifest.xml” this activity is declared with actionMAINand categoryLAUNCHER. This activity is used to configure the service via theSharedPreferencesand start the service by invokingstartServicemethod. In other words, typically the user launches theMainServiceActivityand configures/starts theMainService. - Now consider another activity (Let’s call it
SecondActivity) that is part of another package. Depending on the configuration, the service starts this activity using thestartActivitymethod, so this other activity is running on a separate process than theMainService. As soon as the activity is running, it should inform the service. - At this point, a communication request/reply begins between the
MainServiceand theSecondActivity: the service sends a request and the activity sends a reply.
The communication via messaging might fit, but the MainService is started through startService method, so the bindService method can not be invoked by activities that want to bind to the service.
Then I had an idea that makes use of an additional service (Let’s call it UtilityService), which is part of the same package of MainService: the UtilityService could be started using the bindService method. As a consequence:
- as soon as the
MainServiceis running, it might perform the bind to theUtilityService; - when the
MainServicelaunches an external activity (for example the aboveSecondActivity), this activity bind to theUtilityService.
In this way, both the MainService and the SecondActivity are connected to the UtilityService, where the latter acts as an intermediary for communication.
Are there alternatives to this idea?
You can both bind and start a service, if you wish. It’s a bit unusual, but it can be done.
Binding has nothing in particular to do with services being able to communicate with activities. Using some sort of callback or listener object via binding is a possibility, but it is far from the only one.
You can:
Have the service send a broadcast
Intent, to be picked up by the activityHave the activity send a
PendingIntent(e.g., viacreatePendingResult()) to the service in anIntentextra on the command sent viastartService(), to be used by the service to send information back to the activity (or wherever the activity wants it to go, such as a broadcast)Have the activity pass a
Messengertied to its Handler to the service in anIntentextra on the command sent viastartService(), to be used by the service to send information back to the activityAll of those work perfectly well between processes, as well as within a process.