4

Sorry for bugging you again, but I still can't find a way to make a callback from my activity to a 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();

yet not sure how to integrate that sample into my project.

Any suggestions or links to clear tutorials would be great!

Community
  • 1
  • 1
Roger
  • 6,443
  • 20
  • 61
  • 88
  • How about binding service to your activity and just call its methods, so that you don't really need Observer pattern. – lstipakov Sep 02 '11 at 12:25
  • just please, how do I bind it to be able to call that method? – Roger Sep 02 '11 at 12:27
  • 1
    http://developer.android.com/reference/android/app/Service.html#LocalServiceSample below there is example of client code that you might put into your activity – lstipakov Sep 02 '11 at 12:31

1 Answers1

12

That kind of callbacks (Observer pattern) that you are showing in your example won't work between a service and an activity. Use observer patter when, from class A, you created the instance of class B and want to send callbacks from B to A.

With regards to the services and activities, things are completely different. AFAICT, if you want to callback your Activity from a Service, the best method to achieve this is to use ResultReceiver. There are a lot of interesting things about ResultReceiver:

  • Its constructor receives a Handler (that you must create inside the activity), which will allow you to change UI from the service.
  • It implements Parcelable thus you can put a reference of your ResultReceiver in the Intent extras that you used to start the service.
  • Its onReceive method has a result code integer which allows you to generate different kind of callbacks (this is like if your callback interface had many methods). Also, it receives a Bundle which you can use to put all result data.

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

Cristian
  • 198,401
  • 62
  • 356
  • 264