Android消息机制:Handler浅析

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会造成内存泄漏吗?为什么?怎么解决?

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 222,000评论 6 515
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 94,745评论 3 399
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 168,561评论 0 360
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 59,782评论 1 298
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,798评论 6 397
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 52,394评论 1 310
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,952评论 3 421
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,852评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 46,409评论 1 318
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,483评论 3 341
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,615评论 1 352
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 36,303评论 5 350
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,979评论 3 334
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,470评论 0 24
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,571评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 49,041评论 3 377
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,630评论 2 359