Skip to content

Instantly share code, notes, and snippets.

@sr105
Created December 7, 2014 23:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sr105/96170b875f61239f146d to your computer and use it in GitHub Desktop.
Save sr105/96170b875f61239f146d to your computer and use it in GitHub Desktop.
send command to UI thread using a message containing the command and a place to put the response. The sender waits for the UI using a CountDownLatch
// In background thread:
Handler uiHandler;
public void test() {
Command command = new Command();
// fill command
Response response = send(command);
}
public Response send(Command command) {
CommandAndResponse car = new CommandAndResponse(command);
sendMessage(uiHandler, MESSAGE_COMMAND_AND_RESPONSE, car);
return car.getResponse();
}
public void sendMessage(Handler handler, int what, Object object) {
if (object == null)
return;
handler.obtainMessage(what, object)
.sendToTarget();
}
// in UI thread
public void handleMessage(Message msg) {
if (msg.what == MESSAGE_COMMAND_AND_RESPONSE) {
CommandAndResponse car = (CommandAndResponse) msg.obj;
Response response = handleCommand(car.getCommand());
car.setResponse(response);
}
}
// helper class
public class CommandAndResponse {
private final Command mCommand;
private Response mResponse;
private final CountDownLatch mCountDownLatch;
public CommandAndResponse(Command command) {
mCommand = new Command(command);
mCountDownLatch = new CountDownLatch(1);
}
public void setResponse(Response response) {
synchronized (this) {
mResponse = new Response(response);
}
mCountDownLatch.countDown();
}
public Response getResponse() throws InterruptedException {
mCountDownLatch.await();
synchronized (this) {
return new Response(mResponse);
}
}
public Command getCommand() {
return new Command(mCommand);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment