<<Android 开发艺术探索>> Chapter 10

Android的消息机制

Android消息机制概述

Android的消息机制主要是指Handler的运行机制以及Handler所附带的MessageQueueLooper的工作过程.

  • 一个Thread包含一个Looper
  • 一个Looper包含一个MessageQueue
  • 一个Handler包含一个Looper和一个Messagequeue(和Looper中的是同一个)

Handler通过sendMessage()post()方法将Message放到MessageQueue中, 然后Looper.loop()方法不停的循环从MessageQueue中取Message,成功取出后,通过在loop()中调用message.target.dispatchMessage()方法(message.target其实就是发送MessageHandler)来执行Handler.handleMessage方法.

总结:跨线程的关键是Handler中的Looper是定义Handler时所在Thread的Looper, MessageQueue也是这个Thread的Looper中的MessageQueue,所以之后我们不管在哪个线程调用Handler.sendMessage()方法,Message都会被发送到定义Handler时的LooperMessageQueue中, 因此Handler.dispatchMessage()都是在定义Handler时的那个线程中执行的。

ThreadLocal

ThreadLocal是一个线程内部的数据存储类, 它可以保证, 同一个变量, 在不同的线程中, 使用的都是不同的副本。
Looper就是利用ThreadLocal来保证它在每个Thread中都是独立存在的。

private ThreadLocal<Boolean> mBooleanThreadLocal = new ThreadLocal<Boolean>();
mBooleanThreadLocal.set(true);
Log.d(TAG, "MainThread mBooleanThreadLocal=" + mBooleanThreadLocal.get());

new Thread("Thread1"){
    @Override
    public void run(){
      mBooleanThreadLocal.set(false);
      Log.d(TAG, "Thread1 mBooleanThreadLocal=" + mBooleanThreadLocal.get());
    }
  
  new Thread("Thread1"){
      @Override
      public void run(){
        Log.d(TAG, "Thread2 mBooleanThreadLocal=" + mBooleanThreadLocal.get());
    }
}

输出结果为:

MainThread mBooleanThreadLocal=true
Thread1 mBooleanThreadLocal=false
Thread2 mBooleanThreadLocal=null

从上面的结果中可以发现, 虽然看起来主线程和Thread1Thread2使用的都是同一个ThreadLocal对象, 但是他们其实操作的都是不同的对象。
具体的实现原理可以参考这篇文章

MessageQueue工作原理

MessageQueue主要包含两种操作:插入(enqueueMessage())和读取(next()).
MessageQueue内部实现并不是一个队列, 而是一个单链表.

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 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;
            }
            
            //省略...
        }
    }
}

next()方法其实是一个无限循环的方法,如果消息队列没有消息,那么next()方法会一直堵塞在那里。当有新消息来时,next()方法会返回这条消息并将其从单链表中移除。

Looper工作原理
  • 我们在自定义的Thread中通过Looper.prepare()来进行初始化Thread本身的Looper,通过调用Looper.loop()方法来循环取出MessageQueue中的Message
    Handler在构造方法中从通过Looper.myLooper()方法取出当前ThreadLooper(在Looper.prepare()setsThreadLocal中的Looper)
    new Thread("Thread#1") {
        @Override
        public void run(){
            Looper.prepare();
            Handler handler = new Handler();
            Looper.loop();
        }
    }
    
    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));
    }
    
    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;
        mCallback = callback;
        mAsynchronous = async;
    }  
    
    public static void loop() {
        final Looper me = myLooper();
        final MessageQueue queue = me.mQueue;
        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);
                end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
            } finally {
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }
            //省略...
        }
    }
    
  • Looper会在它的构造方法中初始化属于它的MessageQueue
    private Looper(boolean quitAllowed) {
        mQueue = new MessageQueue(quitAllowed);
        mThread = Thread.currentThread();
    }
    
  • Looper提供了quit()quitSafely()两个方法来退出, 两者的区别是quit()会直接退出, quitSafely()会把MessageQueue()已有的消息处理完后再退出
  • 在子线程中使用完Looper后需要调用quit()方法来退出, 否则那个子线程就会一直处于等待状态
    public void quit() {
        mQueue.quit(false);
    }
    
Handler工作原理

Handler的主要工作包含发送和接收过程。消息的发送可以通过post系列方法以及sendMessage方法实现,但是post的一系列方法最终是通过sendMessage系列方法实现的。
sendMessage系列方法发送一条消息的典型过程如下所示:

public final boolean sendMessage(Message msg){
    return sendMessageDelayed(msg, 0);
}

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

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

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

可以发现Handler发送消息的过程仅仅是向MessageQueue插入了一条消息,MessageQueue通过next方法就会将这条Message返回给Looper,最终消息由Looper交由Handler处理,即HandlerdispatchMessage方法会被调用,这时Handler就进入了消息处理的阶段。dispatchMessage()如下所示:

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

首先,检查msg.callback是否为null, 不为null就通过handleCallback()来处理消息。
其次,如果mCallback 不为null,就通过mCallback.handleMessage(msg)来处理消息。
最后,调用最常见的handleMessage(msg)来处理消息。

  • msg.callback就是我们调用Handlerpost系列方法所传递的Runnable参数。
  • mCallback是一个接口,Handler提供了一个构造方法,使我们可以传递一个Callback作为参数,这样我们就不用重写Handler
    public interface Callback {
        public boolean handleMessage(Message msg);
    }
    
    Handler handler = new Handler(callback);
    
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 157,298评论 4 360
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 66,701评论 1 290
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 107,078评论 0 237
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,687评论 0 202
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,018评论 3 286
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,410评论 1 211
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,729评论 2 310
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,412评论 0 194
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,124评论 1 239
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,379评论 2 242
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,903评论 1 257
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,268评论 2 251
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,894评论 3 233
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,014评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,770评论 0 192
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,435评论 2 269
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,312评论 2 260

推荐阅读更多精彩内容