Created
December 7, 2014 23:22
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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