Android two-way service communication [closed]

2019-09-21 03:28发布

问题:

I have an activity and a local bound service. I've got the bound service up and running fine, so I can handle communication from the client to the server, through functions on the server/binder interface.

However I need two way communication, the service at some point will need to notify the activity (and the user) that something as happened, and needs to wait for a user action before proceeding. In other words, I need the servers calls to the clients to be synchronous or blocking. I.e. when the service calls a function it will pass a few parameters over to the client, which will trigger an AlertDialog for the user to use, and their options will determine the return status code sent back to the service. Until this point, I want the Service to halt and wait until it has recieved the response, which will then determine what it does from there (service continues to run, service shuts down etc.)

So is there a way in Android to do this? I need to get a reference to my activity, and it also needs to expose these blocking methods so I can call them from the service and then wait for a response. I've got an interface for my client activity, but I'm struggling on how to get this over to the service. I don't want to use Serialization and add the reference as an Intent extra, as both the client and service have many members which I do not want to be Serializable.

Thanks.

回答1:

  1. You can use BroadCasts to send info from service to Activity.
  2. Every call of startService() inside Activity class will just call onStartCommand() method of service class, so you can send message to it inside Intent.
  3. Use Service binding to make your own info transfer.