Question

How can I get back a Message reply to the Activity in Android? Say an Activity ask one of a java object (Running Thread) to do something and give back the reply. How java object can know to reply back to the activity who sent the message? I have many activities and many objects communicate with each other.
How can I implement this with Android Messages? I don't want to use broadcasting here.

Was it helpful?

Solution

We can use Messenger for this. Can set the messenger as the reply path. And inside message it hold the handler it should give back the reply.

final Messenger messenger = new Messenger(handler); 
. 
.
msg.replyTo = messenger;  // set the handler of the reply activity.
msg.setData(mBundle);     // if any additional data available put to a bundle
destinationClass.mHandler.sendMessage(msg);



// in destination class

Messenger msger = msg.replyTo;  // get the message sender's details.

Message msg2 = Message.obtain();
msger.send(msg2);                // send the reply message again to the sender

OTHER TIPS

You can use a Handler if you are trying to communicate with a Thread. From the docs

Handler is part of the Android system's framework for managing threads. A Handler object receives messages and runs code to handle the messages.

A nice article on this topic: AndroidBackgroundProcessing

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top