Communication between two different processes (a service and an activity) in Android can be managed via Messenger or AIDL: it is sufficient that an activity binds to a service.
However, what happens if this activity has one or more sub-activity?
From the moment when the main activity starts a sub-activity, I would like the communication to be redirected to the sub-activity; similarly, when the sub-activity is destroyed, I would like the communication is redirected back to the main activity, etc..
Example # 1:
- MyService <—IPC—> MainActivity
- MainActivity launches SubActivity, then MyService <—IPC—> SubActivity
- SubActivity is destroyed, then MyService <—IPC—> MainActivity
Example # 2:
- MyService <—IPC—> MainActivity
- MainActivity launches FirstSubActivity, then MyService <—IPC—> FirstSubActivity
- FirstSubActivity launches SecondSubActivity, then MyService <—IPC—> SecondSubActivity
- SecondSubActivity is destroyed, then MyService <—IPC—> FirstSubActivity
- FirstSubActivity is destroyed, then MyService <—IPC—> MainActivity
How to handle these cases?
You want to have a single entity that is responsible for binding to the service and holding on to the connection and you need that entity NOT to be an Activity instance. Try this:
In this way you don’t have to worry about creating and tearing down connections between the different activities and your service. There is only ever one connection between your entire application (all the activities) and your service.
I realize that I haven’t explained all the gory details, but hopefully you get the basic idea.