Skip to content
Search

Android.os.Handler

lastmod 2018-08-17created 2014-02-244 edits

What is Handler

  • A general-purpose class for interaction between threads
  • A worker thread (= child thread) delivers a Message or Runnable (work to be processed on the parent thread) to the parent thread (= the thread that created the Handler object) (send/post methods)
  • Messages and Runnables delivered from a child thread through the handler go into the parent thread's message queue
  • Internally, a Runnable is also eventually converted into a Message (Message.callback=runnable) and goes into the message queue
  • The thread that created the Handler object (the parent thread) must have set up a MessageQueue through a Looper
  • The UI thread (= main thread) is created by ActivityThread.main(), where a message queue for the UI thread is already created through a Looper, so we do not need to create a message queue for the UI thread
  • The HandlerThread class is for easily creating a thread that has a Looper

Example

// --------------
// Event handler.
// --------------

/** 이벤트 핸들러. */
private static class EventHandler extends Handler {

    /** 비디오화면(View)이 마지막에 도착하였다. */
    public static final int kMessageVideoViewGoEnd = 0x00000001;
    /** 비디오화면(View)이 마지막에서 다시 돌아간다(다시 마지막이 아니다). */
    public static final int kMessageVideoViewReturnEnd = 0x00000002;

    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {
        case kMessageVideoViewGoEnd:
            break;
        case kMessageVideoViewReturnEnd:
            break;
        }
        // super.handleMessage(msg);
    }
}

private EventHandler _event_handler = new EventHandler();

/** 비디오화면(View)이 마지막에 도착하였다. */
public void sendMessageGoEnd() {
    Message msg = _event_handler.obtainMessage(EventHandler.kMessageVideoViewGoEnd);
    _event_handler.sendMessage(msg);
}

/** 비디오화면(View)이 마지막에서 다시 돌아간다(다시 마지막이 아니다). */
public void sendMessageReturnEnd() {
    Message msg = _event_handler.obtainMessage(EventHandler.kMessageVideoViewReturnEnd);
    _event_handler.sendMessage(msg);
}

Favorite site

References


  1. Android_Handler_Story_-_Handler_and_Looper.pdf ↩

  2. Android_Handler_Story_-_Messenger_Service.pdf ↩

  3. Android_how_to_use_handler.pdf ↩