Android handle-message的發送與處理案例詳解

1、Handle,MessageQueue,Message類圖

Handle: 處理消息,並提供一系列函數幫忙我們創建消息和插入消息到消息隊列中

創建handle實例–PbapClientConnectionHandler

mHandlerThread = new HandlerThread("PBAP PCE handler", Process.THREAD_PRIORITY_BACKGROUND);
mHandlerThread.start();
//將這個線程設置為消息處理Looper線程
mConnectionHandler = new PbapClientConnectionHandler.Builder().setLooper(mHandlerThread.getLooper()).setContext(mService).setClientSM(PbapClientStateMachine.this).setRemoteDevice(mCurrentDevice).build();

Looper作用:Looper的prepare函數將Looper和調用prepare的線程綁定在一起,調用線程調用loop函數處理來自該消息隊列的消息。

Android 系統的消息隊列和消息循環都是針對具體線程的,一個線程可以存在(當然也可以不存在)一個消息隊列和一個消息循環(Looper),特定線程的消息隻能分發給本線程,不能進行跨線程通訊。但是創建的工作線程默認是沒有消息循環和消息隊列的,如果想讓該線程具有消息隊列和消息循環,需要在線程中首先調用Looper.prepare()來創建消息隊列,然後調用Looper.loop()進入消息循環

MessageQueue:消息隊列,Handle和Looper中使用的是同一個消息隊列

2、發送消息

  3、處理消息

looper處理消息:

loop 使消息循環起作用,取消息,處理消息

/**

     * Run the message queue in this thread. Be sure to call

     * {@link #quit()} to end the loop.

     */

    public static void loop() {

        final Looper me = myLooper();//返回保存在調用線程TLV中的Looper對象

        if (me == null) {

            throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");

        }

        final MessageQueue queue = me.mQueue;//取得Looper對象的消息隊列

        // Make sure the identity of this thread is that of the local process,

        // and keep track of what that identity token actually is.

        Binder.clearCallingIdentity();

        final long ident = Binder.clearCallingIdentity();

        for (;;) {

            Message msg = queue.next(); // might block 取消息隊列中的一個待處理消息

            if (msg == null) {

                // No message indicates that the message queue is quitting.

                return;

            }

            // This must be in a local variable, in case a UI event sets the logger

            Printer logging = me.mLogging;

            if (logging != null) {

                logging.println(">>>>> Dispatching to " + msg.target + " " +

                        msg.callback + ": " + msg.what);

            }
            msg.target.dispatchMessage(msg);//調用該消息的Handle,交給它的dispatchMessage函數處理
        }
    }

Handle -dispatchMessage

/**
  * Handle system messages here.
  */
public void dispatchMessage(Message msg) {
    if (msg.callback != null) {
    //Message的callback不為空,則直接調用Message的callback來處理消息
        handleCallback(msg);
    } else {
        if (mCallback != null) {
            //Handle的全局Callback不為空
            if (mCallback.handleMessage(msg)) {
                return;
            }
        }
        //調用handle子類的handleMessage來處理消息
        handleMessage(msg);
    }
}

Message.callback用法:將Runnable當做一個Message

Runnable線程處理使用實例

mHandler.post(new Runnable() {
    @Override
    public void run() {
        final IBinder b = callbacks.asBinder();
    });
}

到此這篇關於Android handle-message的發送與處理案例詳解的文章就介紹到這瞭,更多相關Android handle-message內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: