Android Event Loop Pattern

Alex Egg,

This is a handy android version of an Even Loop design pattern, that I discovered today. My particular use case was that I need to do socket communication w/ a embedded device that only open 1 connection at a time. This constraint forces you to share the connection through a central controller. The event loop reads and then writes messages that are queued. This is as opposed each write and read command opening and closing the socket.

 public class CommandHandler extends Handler {
    public CommandHandler(Looper looper) throws IOException {
        this.sendEmptyMessage(READ); //start the loop


    public void handleMessage(Message msg) {
        switch (msg.what) {
        case SEND_COMMAND:
          //queue for send
        case READ:
          //do TCP read
          //do TCP send for queue

            sendEmptyMessage(READ); //restart loop

//start even loop
HandlerThread t = new HandlerThread("CommandHandler");
    commandHandler = new CommandHandler(t.getLooper(), socket);

Permalink: android-event-loop-pattern


Last edited by Alex Egg, 2016-10-05 19:01:04
View Revision History