Android 根据源码分析Handle

1.主线程中的Handle

也许大家开发者都知道Handler主要用于异步消息处理,当一个消息产生后,就会进入队列里(MessageQueue),Loop会取依照一定的顺序取出队列里的消息,交给handle去处理消息。当我们看ActivityThread里的源码时,可以发现主线程是通过handle来回调处理例如Activity的生命周期,Service的状态等。下面就简单分析一下:


Looper.prepareMainLooper();这句代码是初始化Looper的,我们再进入里面方法看看是怎么实现的。


继续跟进prepare(false)中:


继续进去new Looper(quitAllowed))中:


可以看出在Looper里创建了消息队列,继续进入MessageQueue:


最后将false传给了mQuitAllowed,看看哪里调用了这个变量?


下面分析sMainLooper = myLooper();


可发现通过myLooper()方法将本地线程ThreadLocal<Looper>的对象引用给sMainLooper.

sTheadLocal 是Looper类一开始就已经创建的本地线程类.


根据上面的分析,Looper.prepareMainLooper()这个方法是创建了Loop和MessageQueue。

那继续往下看发现:

        if (sMainThreadHandler == null) {
            sMainThreadHandler = thread.getHandler();
        }

其中:

ActivityThread thread = new ActivityThread();

这句话是创建ActivityThread对象,并绑定AMS。



根据上图,thread.getHandler()是返回继续Handle的H对象。

在看H这个类,可发现根据不同的状态值来处理。

然后看到Looper.loop();这句代码才是真正开始循环

 public static void loop() {
        final Looper me = myLooper();//得到Looper实例
        if (me == null) {
            throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
        }
        final MessageQueue queue = me.mQueue;//取出Looper持有的MessageQueue

        // 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 //从队列里取出Message
            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);//对Message进行分发
                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();//消息处理完毕 调用recycleUnchecked()方法进行回收
        }
    }

重点在msg.target.dispatchMessage(msg),这句是实现消息的分发。主线程的target是mH,进入dispatchMessage(msg)


因为mCallback都是空的的,进入handleMessage,所以最后交给子类的handleMessage()处理。

这样整个流程分析完了。


上面就是分析了主线程中的消息处理,原理就是:

  1. 首先通过Looper.prepareMainLooper()初始化Looper,通过prepare(false)这个方法创建不能退出的消息队列,然后通过myLooper()返回本地线程ThreadLocal 中的Looper对象引用交给sMainLooper。
  2. 通过sMainThreadHandler指向getHandler()返回值。
  3. 通过Looper.loop()开启循环,进行信息的分发。

实际上Handler自己产生Message和自己处理Message。

2.源码分析Handle

首先我们使用handler的时候会发现会有两种写法:

第一种情况:

Message msg = new Message();

msg.what = xxxx;

msg.arg1 = xxxx;

mHandle.sendMessage(msg);

第二种情况:

Message msg = mHandler.obtainMessage();

msg.what = xxx;

msg.arg1 = xxx;

mHandler.sendMessage(msg);

下面就从源码去分析这两种有什么区别?


看到obtainMessage()调用了Message.obtain(this);

继续跟进Message.obtain(this):


最后也是返回message,

但是有一句Message m = obtain();看看里面做了什么操作?


最后还是创建了Message对象。

通过上面的代码,很容易看出这是一个链表结构,spool是当前的message,而next是当前的message的下个message.

如果sPool不等于空,就取出头部的Message,然后链表投往后移动。但是这时候就会有疑问?那什么时候message是怎么加入这个链表呢?

往 下看,会发现有一个方法:

这个方法是在recycle()内调用。从上述代码可以轻易看出spool加入了头部。那这个方法什么时候调用呢?这里先说明一下,这个方法是在Message处理完成后调用的,在loop()方法里调用,并将这个对象加入到对象池。另外也有一种情况,是在Message中的enqueueMessage(Message msg,long when)中调用的,当调用Looper.quit()时,就会销毁队列并且也回收Message。当前Looper.loop()不会自动退出,当通过调用Looper.quit()或者Looper.quitSafely()就会退出。

总而言之:handle.obtain()也会调用new Message(),但是从性能的角度来看,handle.obtain()更好,因为内部有缓存的优势。


Handle里面的方法:

SendMessage(Message msg);

SendMessageDelayed(Message msg,long delaymillis);

sendMessageAtTime(Message msg,long uptimeMillis);

enqueueMessage(MessageQueue queue,Message msg,long uptimeMillis);

自上而下依次往下调用。也就是最后调用enqueueMessage(MessageQueue queue,Message msg,long uptimeMillis);

SendEmptyMessage(int what);

SendEmptyMessageDelayed(int what,long delaymillis);

SendMessageDelayed(Message msg,long delayMillis);

SendMessageAtTime(Message msg,long uptimeMillis);

enqueueMessage(MessageQueue queue,Message msg,long uptimeMillis);

也是自上而下往下调用,发现最后还是调用enqueueMessage(MessageQueue queue,Message msg,long uptimeMillis);

enqueueMessage()核心代码:

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

而enqueueMessage(Message msg,long when)是在sendMessage(Message msg)调用的。也就是当Handler发送一个message的时候,message是根据它的延时来决定它的队列位置。时间when是什么?


发现是SystemClock.uptimeMillis() + delayMillis,delayMillis是延迟的时间,SystemClock.uptimeMillis()是系统启动开始到调用该方法的毫秒数。

3.Handle执行SendMessage(msg)的背后?

因为上面分析过,SendMessage(msg)最后会执行enqueueMessage(MessageQueue queue,Message msg,long uptimeMillis);那我们直接进入这个方法去看:


因为一开new Handler()会执行Handler(Callback callback,boolean async);


Looper实例不断会从MessageQueue中读取Handler发来的消息,然后调用msg.target.dispatchMessage(msg),把消息交给msg的target也就是相应的handler的dispatchMessage方法去处理



当然handleMessage(Message msg)是一个空方法,因为消息的最终回调是交给我们去处理的。

如下图:


整个流程解释结束。总而言之:

Looper:读取消息

Handle:处理消息

MessageQuenue:存储消息的队列

猜你喜欢

转载自blog.csdn.net/qq_33453910/article/details/80825466