user2771655
user2771655

Reputation: 1082

How to get back a reply through a message in Android activity

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.

Upvotes: 1

Views: 6299

Answers (3)

user2771655
user2771655

Reputation: 1082

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

Upvotes: 7

Ankur Aggarwal
Ankur Aggarwal

Reputation: 2220

A possible approach is Callbacks. Call backs in Java (code explanation) or an observer pattern http://www.vogella.com/articles/DesignPatternObserver/article.html

Upvotes: 0

nedaRM
nedaRM

Reputation: 1827

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

Upvotes: 1

Related Questions