How to make a callback from the Service to action

Sorry to listen to you again, but I still cannot find a way to make a callback from my activity to the service ...

Found a similar question - How to define callbacks in Android?

// The callback interface interface MyCallback { void callbackCall(); } // The class that takes the callback class Worker { MyCallback callback; void onEvent() { callback.callbackCall(); } } // Option 1: class Callback implements MyCallback { void callback() { // callback code goes here } } worker.callback = new Callback(); 

still not sure how to integrate this sample into my project.

Any suggestions or links for cleaning up the tutorials would be great!

+4
source share
1 answer

Similar callbacks (observer pattern) that you show in your example will not work between service and activity. Use an observer application if you created an instance of class B from class A and want to send callbacks from B to A.

As for services and activities, everything is completely different. AFAICT, if you want to cancel your Activity from Service , the best way to achieve this is to use ResultReceiver . There are a lot of interesting things ResultReceiver :

  • Its constructor gets a Handler (which you must create inside the action), which allows you to change the user interface from the service.
  • It implements Parcelable , so you can put the link of your ResultReceiver in the optional Intent functions that you used to run the service.
  • Its onReceive method has an integer result code that allows you to generate different callbacks (it looks like there were a lot of methods in your callback interface). In addition, he receives a Bundle , which you can use to place all the result data.

On the other hand, if you want to make a callback (not sure if this is the right term in this case), from your Activity to your Service , I think you will have to send a broadcast message or something like that.

+8
source

All Articles