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.
MainService
service and MainServiceActivity
activity. In the file "AndroidManifest.xml" this activity is declared with action MAIN
and category LAUNCHER
. This activity is used to configure the service via the SharedPreferences
and start the service by invoking startService
method. In other words, typically the user launches the MainServiceActivity
and configures/starts the MainService
.SecondActivity
) that is part of another package. Depending on the configuration, the service starts this activity using the startActivity
method, so this other activity is running on a separate process than the MainService
. As soon as the activity is running, it should inform the service.MainService
and the SecondActivity
: 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:
MainService
is running, it might perform the bind to the UtilityService
;MainService
launches an external activity (for example the above SecondActivity
), this activity bind to the UtilityService
.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?
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.
You can both bind and start a service, if you wish. It's a bit unusual, but it can be done.
Are there alternatives to this idea?
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 activity
Have the activity send a PendingIntent
(e.g., via createPendingResult()
) to the service in an Intent
extra on the command sent via startService()
, 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 Messenger
tied to its Handler to the service in an Intent
extra on the command sent via startService()
, to be used by the service to send information back to the activity
All of those work perfectly well between processes, as well as within a process.