Android消息机制:Handler浅析

2020-09-01  本文已影响0人  EasonZzz

Android的消息机制主要是指Handler的运行机制,Handler的运行需要底层的MessageQueue和Looper的支撑。Android规定访问UI只能在主线程进行,如果在子线程中访问UI,程序会抛出异常,Handler的主要作用就是将一个任务切换到某个指定线程中去执行。如在子线程获取网络数据,再更新页面UI就需要用到handler机制。
Handler主要涉及到四个类:Handler,Message,MessageQueue和Looper

MessageQueue

MessageQueue就是消息队列,但是其内部实现其实并不是队列,而是通过单链表的数据结构来维护消息列表。MessageQueue主要包含插入和读取两个操作,读取操作本身又伴随这删除操作。插入对应的方法是enqueueMessage,读取对应的方法是next。enqueueMessage就是往消息队列中插入一条消息,next是从消息队列中读取一条消息并移除它。

enqueueMessage源码如下:

boolean enqueueMessage(Message msg, long when) {
    //msg.target就是处理消息的handler
    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方法返回一个布尔值,消息成功插入消息队列返回true。方法体内先判断msg.target是不是为空,msg.target其实就是处理消息的handler,handler为空自然就处理不了消息。再判断消息是不是已经被处理了,从这个判断可以得出消息不能被重复处理。接下来的操作就是单链表的插入操作,就不再赘述。如果线程是当前是堵塞状态,最后还会唤起线程。

next方法源码如下:

 Message next() {
    
    ......

    int pendingIdleHandlerCount = -1; // -1 only during first iteration
    int nextPollTimeoutMillis = 0;
    for (;;) {
        if (nextPollTimeoutMillis != 0) {
            Binder.flushPendingCommands();
        }

        //阻塞方法,主要是通过native层的epoll监听文件描述符的写入事件来实现的。
       //nextPollTimeoutMillis=-1,一直阻塞不会超时。
       //nextPollTimeoutMillis=0,不会阻塞,立即返回。
       //nextPollTimeoutMillis>0,最长阻塞nextPollTimeoutMillis毫秒(超时),如果期间有程序唤醒会立即返回。
        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.
                //msg.target == null表示此消息为消息屏障(通过postSyncBarrier方法发送来的)
                //如果发现了一个消息屏障,会循环找出第一个异步消息(如果有异步消息的话),所有同步消息都将忽略(平常发送的一般都是同步消息)                
                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.
            //消息队列被标记为退出状态,返回null
            if (mQuitting) {
                dispose();
                return null;
            }
               ......
        }
        ......
    }
}

next方法是一个无限循环,如果消息队列中没有消息,next方法就会一直阻塞。有新消息时,将新消息返回并移除这条消息。当消息队列被标记为退出状态时,返回null,这里先卖一个关子,这个null会在文章后面讲到。

Looper

Looper在Android消息机制扮演消息循环的角色,会不停的去MessageQueue中查看是否有新消息,如果有就立即处理,没有的话就会一直堵塞在那边。

Looper的构造函数:

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

构造函数中会新建一个MessageQueue,然后将当前的线程对象保存起来。

大家都知道创建Handler之前必须要现在线程中创建一个Looper对象,不然会报错。创建Looper对象也很简单,直接调用Looper.prepare()就可以了,创建Looper对象之后还不能实现消息循环,必须再调用loop()方法来开启消息循环。读到这里可能会有困惑,为什么在主线程创建Handler不需要我们自己创建Looper对象?答案就在ActivityThread里:

public static void main(String[] args) {
    ...
    Looper.prepareMainLooper();
    ...
    ActivityThread thread = new ActivityThread();
    thread.attach(false, startSeq);

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

    if (false) {
        Looper.myLooper().setMessageLogging(new
                LogPrinter(Log.DEBUG, "ActivityThread"));
    }

    // End of event ActivityThreadMain.
    Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
    Looper.loop();

    throw new RuntimeException("Main thread loop unexpectedly exited");
}

从源码中可以看到在主线程启动时就已经调用了Looper.prepareMainLooper()方法,该方法是Looper提供给主线程使用的,接下来又调用了 Looper.loop()开启消息循环。这就是为什么我们在主线程创建Handler时不需要的自己创建Looper对象的原因。

再回过头来开子线程创建Handler的流程:

  thread {
        Looper.prepare()
        val handler = Handler(object : Handler.Callback {
            override fun handleMessage(msg: Message): Boolean {
                doSomething()
            }
        })
        Looper.loop()
    }

首先创建一个Looper对象,接着创建Handler,然后再开启循环。(如上为了方便用kotlin代码进行举例)
Looper提供了创建对象的方法之外还提供了quit和quitSafely方法,两个方法的唯一区别就是quit会立即退出,quitSafely会等消息队列中所有的消息处理完成之后再退出。退出之后Handler的send方法会返回false。不建议在主线程中调取quit方法,因为会立即结束主线程。当子线程中,应当在处理完所有消息之后调取quit方法来结束当前线程。
Looper中最重要的方法就是loop方法,源码如下:

public static void loop() {
    ...
    for (;;) {
        Message msg = queue.next(); // might block
        if (msg == null) {
            // No message indicates that the message queue is quitting.
            return;
        }
        ...  
        try {
            msg.target.dispatchMessage(msg);
            if (observer != null) {
                observer.messageDispatched(token, msg);
            }
            dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
        } catch (Exception exception) {
            if (observer != null) {
                observer.dispatchingThrewException(token, msg, exception);
            }
            throw exception;
        } finally {
            ThreadLocalWorkSource.restore(origWorkSource);
            if (traceTag != 0) {
                Trace.traceEnd(traceTag);
            }
        }
       ...
        msg.recycleUnchecked();
    }
}

loop方法也比较好理解,他也是一个无限循环的方法。for循环中会调取MessageQueue的next方法,在之前说过next是一个阻塞方法,所以当消息队列中没有消息的时候,会一直阻塞在这里,唯一跳出循环的方式就是next方法返回了null,这里就是解答了之前在讲MessageQueue的时候为什么要返回null。当Looper调quit方法的时候,Looper就会调用MessageQueue的quit方法,然后MessageQueue的next方法就会返回null,这样loop方法才能跳出无限循环。当loop拿到了消息之后就会调用msg.target.dispatchMessage(msg)「msg.target前面讲到过就是发送这条消息的Handler」将消息交给Handler来处理了。这里需要注意的是Handler的dispatchMessage是在创建Handler时所使用的Looper中执行的,这就就成功的切换到指定线程中去执行了。

Handler

Handler的作用主要是消息发送以及接收。消息发送可以通过一系列的post方法和一系列的send方法,其实post方法到最后都是通过send方法来进行发送。

public boolean sendMessageAtTime(@NonNull 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);
}

private boolean enqueueMessage(@NonNull MessageQueue queue, @NonNull Message msg,
        long uptimeMillis) {
    msg.target = this;
    msg.workSourceUid = ThreadLocalWorkSource.getUid();

    if (mAsynchronous) {
        msg.setAsynchronous(true);
    }
    return queue.enqueueMessage(msg, uptimeMillis);
}

查看源码发现到最后都是通过MessageQueue的enqueueMessage将消息插入到消息队列中。之后Looper就会调用MessageQueue的next方法拿到消息,然后就进入了下一个Handler处理消息的阶段,调用Handler的dispatchMessage方法。源码如下:

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

1.先判断msg的callback是不是为null,这个callback对象其实就是handler发送消息时调用post方法所传递的Runnable参数,不为空就调用handleCallback方法处理。

 private static void handleCallback(Message message) {
    message.callback.run();
}

handleCallback方法也很简单,直接执行Runnable的run方法。
2.其次检查mCallback是否为null,部位null调用mCallback的handleMessage方法,查看源码mCallBack其实是一个CallBack接口,CallBack具体如下:

public interface Callback {
    /**
     * @param msg A {@link android.os.Message Message} object
     * @return True if no further handling is desired
     */
    boolean handleMessage(@NonNull Message msg);
}

mCallBack通过构造函数传入,当你不想创建继承自Handler的派生类时,就可以通过该构造方法直接传入一个Callback参数来实现消息处理。

val handler = Handler(object :Handler.Callback{
            override fun handleMessage(msg: Message): Boolean {
                ...
           
})

3.最后调用Handler的handleMessage来处理消息

处理消息的流程图大致如下:


image.png

额外注意点:

  1. 消息机制里需要频繁创建消息对象(Message),因此消息对象需要使用享元模式来缓存,以避免重复分配 & 回收内存。具体来说,Message 使用的是有容量限制的、无头节点的单链表的对象池,创建Message的时候最好用Handler的obtainMessage来进行创建,尽量避免使用new Message()来创建造成内存抖动

2.在子线程中创建Handler时一定要先创建Looper对象,然后调用loop方法开启循环

3.尽量使用弱持有来创建Handler对象

思考:

1.一个线程可以创建几个Looper?

2.MessageQueue是否线程安全?如果是 怎么保证?

3.Looper在主线程中死循环,为啥不会ANR?

4.Handler会造成内存泄漏吗?为什么?怎么解决?

上一篇下一篇

猜你喜欢

热点阅读