During the most recent Google IO, there was a presentation about implementing restful client applications. Unfortunately, it was only a high level discussion with no source code of the implementation.
In this diagram, on the return path there are various different callbacks to other methods.
How do I declare what these methods are?
I understand the idea of a callback - a piece of code that gets called after a certain event has happened, but I don't know how to implement it. The only way I've implemented callbacks so far have been overriding various methods (onActivityResult for example).
I feel like I have a basic understanding of the design pattern, but I keep on getting tripped up on how to handle the return path.
No need to define a new interface when you can use an existing one:
android.os.Handler.Callback
. Pass an object of type Callback, and invoke callback'shandleMessage(Message msg)
.In many cases, you have an interface and pass along an object that implements it. Dialogs for example have the OnClickListener.
Just as a random example:
I probably messed up the syntax in option 2. It's early.
You can also use
LocalBroadcast
for this purpose. Here is a quick quideCreate a broadcast receiver:
This is how you can trigger it
unRegister receiver in onPause:
to clarify a bit on dragon's answer (since it took me a while to figure out what to do with
Handler.Callback
):Handler
can be used to execute callbacks in the current or another thread, by passing itMessage
s. theMessage
holds data to be used from the callback. aHandler.Callback
can be passed to the constructor ofHandler
in order to avoid extending Handler directly. thus, to execute some code via callback from the current thread:EDIT: just realized there's a better way to get the same result (minus control of exactly when to execute the callback):
Example to implement callback method using interface.
Define the interface, NewInterface.java.
package javaapplication1;
Create a new class, NewClass.java. It will call the callback method in main class.
The main class, JavaApplication1.java, to implement the interface NewInterface - callback() method. It will create and call NewClass object. Then, the NewClass object will callback it's callback() method in turn.
When something happens in my view I fire off an event that my activity is listening for:
// DECLARED IN (CUSTOM) VIEW
// DECLARED IN ACTIVITY
If you want to know more about communication (callbacks) between fragments see here: http://developer.android.com/guide/components/fragments.html#CommunicatingWithActivity