Android-Handler 消息机制

Handler的使用场景:有时候在子线程中进行耗时的 I/O 操作,在操作完成会需要对UI进行改变,由于Android开发机制限制,我们并不能在子线程修改UI,否则会抛出异常。这个时候可以将更新UI操作通过Handler切换到主线程完成。
以上涉及到的几个概念:
  1>为什么不能在主线程进行耗时操作?
  2>为什么不能在子线程访问UI?

1)Android主线程中进行UI绘制,当进行耗时操作时,UI会停止绘制,界面阻塞程序看起来卡死,这对用户来说是极其糟糕的体验。而且当Android系统发现有在UI线程内进行网络请求时会抛出异常

RuntimeException: Unable to start activity ComponentInfo{com.example/com.example.ExampleActivity}: android.os.NetworkOnMainThreadException

2)最直观体现在更改UI时,ViewRootImpl中通过cheakThread()对UI进行校验。当在子线程中更改UI时会抛出异常。

void checkThread() {

        if (mThread != Thread.currentThread()) {

            throw new CalledFromWrongThreadException(

                    "Only the original thread that created a view hierarchy can touch its views.");

        }
}

我们考虑下为什么系统不允许在子线程中访问UI呢?这是因为Android的UI控件不是线程安全的,如果在多线程中并发访问可能会造成UI控件处于不可预期的状态。好为什么系统不对UI控件访问加上锁机制呢?缺点有两个:首先加上锁机制会让UI访问的逻辑变的复杂;其次锁机制会降低UI访问的效率。源自----《Android开发艺术探索》

Tips:其实在Activity的onCreate中进行不太耗时的操作是可以在子线程中更新UI的。因为checkThread方法是在界面初始化完成绘制(onWindowFocusChanged)后进行调用判断。而在onCreate方法中界面UI还未完成渲染,不用调用checkThread方法,所以此时在对于不太耗时的操作在子线程中可以更新UI。

消息传递原理

好的,现在我们正式了解Handler机制,完成整个消息传递过程需要Handler、MeaasgeQueue、Looper、Meaasge四个对象。
大致和流程为:Handler通过sendMessage发送消息(Message),发送的消息存放在消息队列(MessageQueue)中;主线程中默认创建Looper,而Looper的looper()方法会不停去消息队列(messageQueue)中获取消息(msg),当有发现有新消息(msg != null)时则传递给Handler的dispatchMessage()进行处理,内部即调用handleMessage()完成消息传递。

1首先通过handler.sendMessage(Message msg)发送消息,我们去源码看看

    //调用延迟发送发送
    public final boolean sendMessage(Message msg)
    {
        return sendMessageDelayed(msg, 0);
    }

其实就是调用sendMessageAtTime方法

    public final boolean sendMessageDelayed(Message msg, long delayMillis)
    {
        if (delayMillis < 0) {
            delayMillis = 0;
        }
        return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
    }

在sendMessageAtTime中创建MessageQueue对象用来存放消息(单链表数据结构来维护消息列表),把MeaasgeQueue、Message、延时时间传递到enqueueMessage方法中。

    public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
        MessageQueue queue = mQueue;
        if (queue == null) {
            RuntimeException e = new RuntimeException(
                    this + " sendMessageAtTime() called with no mQueue");
            Log.w("Looper", e.getMessage(), e);
            return false;
        }
        return enqueueMessage(queue, msg, uptimeMillis);
    }

接着我们来看enqueueMessage方法,其中msg.target = this 是此handler将自己作为一个标记传入到了Message中。(此target后文会用到)

private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
        msg.target = this;
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        return queue.enqueueMessage(msg, uptimeMillis);
    }

MessageQueue的enqueueMessage()主要是实现单链表的插入操作;next()方法是一个无限循环的方法,如果消息队列中没有消息,那next方法会一直阻塞在这里,当有新消息到来,next方法会条消息并将其从单链表中删除

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;
    }

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;
        }
    }
Looper工作原理

一个线程中必须也只能有一个Looper,UI线程中默认创建Looper对象,子线程中可以通过 Looper.prepare()创建Looper,并调用Looper.looper()方法实现去MessageQueue中轮循Message.(可调用Looper的quit方法终止消息循环)

Looper.prepare()内会调用以下方法创建MessageQueue消息队列

    private Looper(boolean quitAllowed) {
        mQueue = new MessageQueue(quitAllowed);
        mThread = Thread.currentThread();
    }

下面再来看looper方法,可以看到looper方法是一个死循环,唯一跳出循环的方式是MeaasgeQueue的next方法(msg)返回了null。当返回不为空时,走msg.target.dispatchMessage(msg);其中此时target即为前面Message中标记的Handler对象,所以就是调用了handler.dispatchMessage()方法

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 traceTag = me.mTraceTag;
            if (traceTag != 0) {
                Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
            }
            try {
                 //关键代码(如下)-------------------------------------
                 msg.target.dispatchMessage(msg);
                //关键代码(往上)-------------------------------------
            } finally {
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }

            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();
        }
    }

再看Handler的dispatchMessage方法,在日常开发中创建Handler并重写handleMessage方法时,callback(就是Runnable)为null,看到最后调用了handleMessage方法也就是回到我们重写的handleMessage方法。最终完成了的消息传递过程。

    public void dispatchMessage(Message msg) {
        if (msg.callback != null) {
            handleCallback(msg);
        } else {
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            handleMessage(msg);
        }
    }

补充:以上可知Handler中创建了MessageQueue,但是这个消息队列如何跟Looper中消息队列的关联起来呢?其实在Handler的构造函数中获取到Looper对象,将Looper中的queue赋值给Handler中queue,所以Handler跟Looper中的MessageQueue对象是一样的。

    public Handler(Callback callback, boolean async) {
      ......
        mLooper = Looper.myLooper();
        if (mLooper == null) {
            throw new RuntimeException(
                "Can't create handler inside thread that has not called Looper.prepare()");
        }
        mQueue = mLooper.mQueue;
      ......
    }

有关Handler消息传递机制的大致到这里,如有问题,欢迎指正~

参考:《Android开发艺术探索》

你可能感兴趣的:(Android-Handler 消息机制)