Android - using android.os.Mailbox for asychronous communication
Here is a screen shot.

Here’s how you set up a new Mailbox
// Create a mailbox and publish it.
Mailbox.createAndPublish("MyMailbox", new MyReceiver());
MyReceiver snippet and Notes
- when we get a message with msg.what == TEST1, we add another entry in the hash map and send it back
- when we get a message with msg.what == TEST2, we throw an exception
- for TEST3 and TEST4, we just send the message after a delay, just to illustrate that we can send the response asynchronously
/**
* Receiver for the Mailbox
*/
private class MyReceiver extends Handler implements Mailbox.Receiver {
public Object onNewMail(final Message msg, final Mailbox.Completion completion) {
switch (msg.what) {
case TEST1:
HashMap map = msg.getData();
map.put("hello", "world");
return map;
case TEST2:
throw new RuntimeException();
case TEST3:
completion.setAutoComplete(false);
// Send response after 5 seconds.
postDelayed(new Runnable() {
public void run() {
HashMap map = msg.getData();
map.put("hello", "world");
completion.complete(map);
}
}, 5000L);
return null;
case TEST4:
completion.setAutoComplete(false);
// Send exception after 5 seconds.
postDelayed(new Runnable() {
public void run() {
completion.completeWithException(new RuntimeException());
}
}, 5000L);
return null;
default:
throw new RuntimeException("Got unknown message " + msg);
}
}
}
Sending messages to the mailbox
Not too complicated..
// Setup request/response data structures
Message request = handler.obtainMessage(TEST4);
HashMap map = new HashMap();
map.put("test.name", "test4");
request.setData(map);
Message response = handler.obtainMessage(RESPONSE);
// Send the request to the mailbox
Mailbox.sendToPublished("MyMailbox", request, response);
Receiving the response back from the mailbox
Just another Handler..
/**
* Handler updates the text area with the response or exception
*/
private class MyUIReceiver extends Handler {
public void handleMessage(android.os.Message message) {
switch (message.what) {
case RESPONSE:
TextView text = (TextView) MyMailbox.this.findViewById(R.id.text);
AsyncResult result = (AsyncResult) message.obj;
if (result.exception != null) {
text.setText(result.exception.toString());
} else {
text.setText(result.result.toString());
}
break;
}
}
}
Saving the best for last!!
- You can send messages from another process not just the same process!
- Looks like you can stuff any Parcelable object into the hashmap (and don’t have to stick to just AIDL!!)
Download Source and APK from here - Mailbox.zip
About this entry
You’re currently reading “Android - using android.os.Mailbox for asychronous communication,” an entry on Show me the code! - By Davanum Srinivas
- Published:
- 12.27.07 / 2pm
- Category:
- Uncategorized
- Tags:
1 Comment
Jump to comment form | comments rss [?] | trackback uri [?]