瞭解Handler,Looper, MessageQueue,Message的工作流程

Handler的作用

異步通信,消息傳遞

Handler的基本用法

Handler的用法,示例1、(子線程向主線程發送消息)

public class HandlerActivity extends AppCompatActivity {
Handler handler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        Toast.makeText(HandlerActivity.this, "接收到了消息", Toast.LENGTH_SHORT).show();
    }
};
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_handler);

}

public void onClickView(View v) {
    switch (v.getId()) {
        case R.id.button: {
            Thread thread = new Thread() {
                @Override
                public void run() {
                    Message msg = Message.obtain();
                    handler.sendMessage(msg);
                }
            };
            thread.start();
            break;
        }
    }
}
}

這個界面只有一個Button, 點擊事件是:啓動一個線程,在這個線程裏使用handler,發送一個消息;這個消息不帶任何數據。
Message: 這個可以使用new來生成,但是最好還是使用Message.obtain()來獲取一個實例。這樣便於消息池的管理。
handler初始化的時候,我們複寫了handleMessage方法,這個方法用來接收,子線程中發過來的消息。

示例2、主線程向子線程發送消息

public class HandlerActivity extends AppCompatActivity {
Handler handler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        Log.d("child", "----" + Thread.currentThread().getName());
    }
};
Handler childHandler = null;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_handler);
    Thread child = new Thread("child thread") {
        @Override
        public void run() {
            Looper.prepare();
            childHandler = new Handler(Looper.myLooper()) {
                @Override
                public void handleMessage(Message msg) {
                    Log.d("child", "----" + Thread.currentThread().getName() + ",  " + msg.obj);
                }
            };
            Looper.loop();
        }
    };
    child.start();
}

public void onClickView(View v) {
    switch (v.getId()) {
        case R.id.button: {
            Thread thread = new Thread() {
                @Override
                public void run() {
                    Message msg = Message.obtain();
                    handler.sendMessage(msg);
                }
            };
            thread.start();
            break;
        }
        case R.id.button1: {
            if (childHandler != null) {
                Message msg = Message.obtain(childHandler);
                msg.obj = "123---" + SystemClock.uptimeMillis();
                childHandler.sendMessage(msg);

            } else {
                Log.d("-----", "onClickView: child Handler is null");
            }

            break;
        }
    }
}
}

主線程向子線程發送消息時,我們需要使用的是handler,但是這個handler是需要在子線程中實例化,否則子線程無法接收到消息。
在child thread中準備的工作:

    1. Looper.prepare();
    1. 實例化childHandler的時候出入了一個Looper實例。
    1. Looper.loop()調用
      假如我們直接在子線程中直接實例化一個handler,而不傳入Looper實例。程序會直接拋出異常:
      java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
      這個異常是在hanlder源碼:

      public Handler(Callback callback, boolean async) {
      if (FIND_POTENTIAL_LEAKS) {
      final Class<? extends Handler> klass = getClass();
      if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&
      (klass.getModifiers() & Modifier.STATIC) == 0) {
      Log.w(TAG, "The following Handler class should be static or leaks might occur: " +
      klass.getCanonicalName());
      }
      }
      mLooper = Looper.myLooper();
      if (mLooper == null) {
      throw new RuntimeException(
      "Can't create handler inside thread that has not called Looper.prepare()");
      }

      mQueue = mLooper.mQueue;
      mCallback = callback;
      mAsynchronous = async;
      }
      出現的,從這裏可知,在線程中實例化一個handler需要一個Looper實例。

      如果其他線程的實例出來的Looper會怎麼樣?

      首先看Looper源碼中是怎麼寫的。Looper的構造方法是私有的,這樣我們只能通過Looper的靜態方法來實例化一個Looper.在Looper類中還有一個ThreadLocal<Looper> sThreadLocal 變量,而在上面的代碼中使用了Looper.myLooper()方法來給handler一個Looper實例。

      * Looper.myLooper()

      public static @Nullable Looper myLooper() {
      return sThreadLocal.get();
      }

      這個方法返回了一個存放在ThreadLocal<Looper>中的Looper實例。

      爲什麼在調用Looper.myLooper()方法之前需要先調用 Looper.prepare()呢?

      Looper.prepare源碼:

    public static void prepare() {
    prepare(true);
    }
    private static void prepare(boolean quitAllowed) {
    if (sThreadLocal.get() != null) {
    throw new RuntimeException("Only one Looper may be created per thread");
    }
    sThreadLocal.set(new Looper(quitAllowed));
    }
    方法很簡單,就是檢查sThreadLocal裏面是否有有值,然後將Looper的實例存放到ThreadLocal,如果不爲空,直接就是 RuntimeException 異常。這也保證了一個線程中只能有一個Looper實例。因此,Looper.prepare方法只能調用一次。

    那麼ThreadLocal的作用是什麼呢?

    在這個程序中,可以大概理解成線程間數據的隔離。意思就是我存放在ThreadLocal中的數據,只能在我本線程中可以獲得到值,在其他線程中獲取不到(其他線程中獲取的是null)。
    這樣就能得出,其他線程中的Looper,在本線程中通過Looper.myLooper()獲取不到數據。

    那麼爲什麼在主線程中不需要傳入Looper實例呢?

    通過查找Android源碼,可以知道在ActivityThread中main方法裏面,UI線程已經初始化了Looper.prepareMainLooper();這樣就在UI線程中有Looper實例了。當然在main方法的下面,也調用了Looper.loop()方法。

    Looper.loop()方法是做什麼的

    public static void loop() {
    final Looper me = myLooper();
    if (me == null) {
    throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
    }
    final MessageQueue queue = me.mQueue;
    // 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
        final Printer logging = me.mLogging;
        if (logging != null) {
            logging.println(">>>>> Dispatching to " + msg.target + " " +
                    msg.callback + ": " + msg.what);
        }
    
        final long slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;
    
        final long traceTag = me.mTraceTag;
        if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
            Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
        }
        final long start = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
        final long end;
        try {
            msg.target.dispatchMessage(msg);
            end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
        } finally {
            if (traceTag != 0) {
                Trace.traceEnd(traceTag);
            }
        }
        if (slowDispatchThresholdMs > 0) {
            final long time = end - start;
            if (time > slowDispatchThresholdMs) {
                Slog.w(TAG, "Dispatch took " + time + "ms on "
                        + Thread.currentThread().getName() + ", h=" +
                        msg.target + " cb=" + msg.callback + " msg=" + msg.what);
            }
        }
    
        if (logging != null) {
            logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
        }
    
        // Make sure that during the course of dispatching the
        // identity of the thread wasn't corrupted.
        final long newIdent = Binder.clearCallingIdentity();
        if (ident != newIdent) {
            Log.wtf(TAG, "Thread identity changed from 0x"
                    + Long.toHexString(ident) + " to 0x"
                    + Long.toHexString(newIdent) + " while dispatching to "
                    + msg.target.getClass().getName() + " "
                    + msg.callback + " what=" + msg.what);
        }
    
        msg.recycleUnchecked();
    **}**

    }

這個方法裏面,我們需要注意到:

  1. Looper me這個不允許爲空
  2. for (;;)循環
  3. Message msg = queue.next()
  4. msg.target.dispatchMessage(msg);

  5. 在looper.loop方法裏面,檢查了本線程中的Looper實例,也對應了在調用looper.loop方法之前必須先調用looper.prepare方法。
  6. for循環是一個死循環,這個需要一直取出MessageQueue隊列中的數據,也就是剛纔所列的第三個 queue.next方法。這個方法會阻塞,直到有消息從消息隊列中取出來。
    next方法源碼:

    Message next() {
    // Return here if the message loop has already quit and been disposed.
    // This can happen if the application tries to restart a looper after quit
    // which is not supported.
    final long ptr = mPtr;
    if (ptr == 0) {
        return null;
    }
    int pendingIdleHandlerCount = -1; // -1 only during first iteration
    int nextPollTimeoutMillis = 0;
    for (;;) {
        if (nextPollTimeoutMillis != 0) {
            Binder.flushPendingCommands();
        }
    
        nativePollOnce(ptr, nextPollTimeoutMillis);
    
        synchronized (this) {
            // Try to retrieve the next message.  Return if found.
            final long now = SystemClock.uptimeMillis();
            Message prevMsg = null;
            Message msg = mMessages;
            if (msg != null && msg.target == null) {
                // Stalled by a barrier.  Find the next asynchronous message in the queue.
                do {
                    prevMsg = msg;
                    msg = msg.next;
                } while (msg != null && !msg.isAsynchronous());
            }
            if (msg != null) {
                if (now < msg.when) {
                    // Next message is not ready.  Set a timeout to wake up when it is ready.
                    nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
                } else {
                    // Got a message.
                    mBlocked = false;
                    if (prevMsg != null) {
                        prevMsg.next = msg.next;
                    } else {
                        mMessages = msg.next;
                    }
                    msg.next = null;
                    if (DEBUG) Log.v(TAG, "Returning message: " + msg);
                    msg.markInUse();
                    return msg;
                }
            } else {
                // No more messages.
                nextPollTimeoutMillis = -1;
            }
    
            // Process the quit message now that all pending messages have been handled.
            if (mQuitting) {
                dispose();
                return null;
            }
    
            // If first time idle, then get the number of idlers to run.
            // Idle handles only run if the queue is empty or if the first message
            // in the queue (possibly a barrier) is due to be handled in the future.
            if (pendingIdleHandlerCount < 0
                    && (mMessages == null || now < mMessages.when)) {
                pendingIdleHandlerCount = mIdleHandlers.size();
            }
            if (pendingIdleHandlerCount <= 0) {
                // No idle handlers to run.  Loop and wait some more.
                mBlocked = true;
                continue;
            }
    
            if (mPendingIdleHandlers == null) {
                mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)];
            }
            mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers);
        }
    
        // Run the idle handlers.
        // We only ever reach this code block during the first iteration.
        for (int i = 0; i < pendingIdleHandlerCount; i++) {
            final IdleHandler idler = mPendingIdleHandlers[i];
            mPendingIdleHandlers[i] = null; // release the reference to the handler
    
            boolean keep = false;
            try {
                keep = idler.queueIdle();
            } catch (Throwable t) {
                Log.wtf(TAG, "IdleHandler threw exception", t);
            }
    
            if (!keep) {
                synchronized (this) {
                    mIdleHandlers.remove(idler);
                }
            }
        }
    
        // Reset the idle handler count to 0 so we do not run them again.
        pendingIdleHandlerCount = 0;
    
        // While calling an idle handler, a new message could have been delivered
        // so go back and look again for a pending message without waiting.
        nextPollTimeoutMillis = 0;
    }

    }

  7. queue.next方法,返回一個Message,而這個message會被傳入到msg.target的dispatchMessage方法中。msg.target是一個handler,就是發送消息的實例。
    dispatchMessage(Message)源碼:
    public void dispatchMessage(Message msg) {<br/>if (msg.callback != null) {<br/>handleCallback(msg);<br/>} else {<br/>if (mCallback != null) {<br/>if (mCallback.handleMessage(msg)) {<br/>return;<br/>}<br/>}<br/>handleMessage(msg);<br/>}<br/>}<br/>
    Handler初始化的時候,我們並沒有傳入msg.callback和mCallback這兩個回調。所以這個方法最終執行的是handleMessage方法。
    上面我們分析了ThreadLocal,Looper,Message,MessageQueue,下面開始分析handler發送消息的方式。

    Handler發送消息

    Handler 通過sendMessage方法發送消息。這個方法最終調用的是

private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {<br/>msg.target = this;<br/>if (mAsynchronous) {<br/>msg.setAsynchronous(true);<br/>}<br/>return queue.enqueueMessage(msg, uptimeMillis);<br/>}<br/>
參數:MessageQueue queue則是Handler中mQueue變量,這個變量在Handler(Callback callback, boolean async)初始化完成。它是Looper中一個final MessageQueue的變量,在初始化Looper的時候,就開始初始化MessageQueue。這也是一個線程中只有一個MessageQueue的原因.
Message msg 是封裝的消息。
long uptimeMillis 延遲發送時間。
之前分析looper.loop方法的時候,說了msg.target.dispatchMessage, 這個target就是在這個方法裏面賦值的。
從這個方法裏面,可以知道handler的sendMessage,只是把消息(Message實例)添加到了queue隊列中。

    boolean enqueueMessage(Message msg, long when) {
    if (msg.target == null) {
        throw new IllegalArgumentException("Message must have a target.");
    }
    if (msg.isInUse()) {
        throw new IllegalStateException(msg + " This message is already in use.");
    }
    synchronized (this) {
        if (mQuitting) {
            IllegalStateException e = new IllegalStateException(
                    msg.target + " sending message to a Handler on a dead thread");
            Log.w(TAG, e.getMessage(), e);
            msg.recycle();
            return false;
        }

        msg.markInUse();
        msg.when = when;
        Message p = mMessages;
        boolean needWake;
        if (p == null || when == 0 || when < p.when) {
            // New head, wake up the event queue if blocked.
            msg.next = p;
            mMessages = msg;
            needWake = mBlocked;
        } else {
            // Inserted within the middle of the queue.  Usually we don't have to wake
            // up the event queue unless there is a barrier at the head of the queue
            // and the message is the earliest asynchronous message in the queue.
            needWake = mBlocked && p.target == null && msg.isAsynchronous();
            Message prev;
            for (;;) {
                prev = p;
                p = p.next;
                if (p == null || when < p.when) {
                    break;
                }
                if (needWake && p.isAsynchronous()) {
                    needWake = false;
                }
            }
            msg.next = p; // invariant: p == prev.next
            prev.next = msg;
        }

        // We can assume mPtr != 0 because mQuitting is false.
        if (needWake) {
            nativeWake(mPtr);
        }
    }
    return true;
}

Handler, Looper, Message, MessageQueue之間的關係

通過handler發送Message,將Message壓入MessageQueue隊列中;而Looper.loop方法又在不停的循環這個消息隊列,取出壓入MessageQueue的Message, 然後dispatchMessage分發,最終會調用handler.handleMessage方法來處理髮送過來的Message.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章