Last Updated: February 25, 2016
·
2.944K
· eggie5

Android Event Loop Pattern

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 {
        super(looper);
        this.sendEmptyMessage(READ); //start the loop

    }

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

            sendEmptyMessage(READ); //restart loop
            break;
        default:
            super.handleMessage(msg);
        }
    }
}

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