结合源码理解Android消息机制

Android的消息机制指的是HandlerLooperMessageQueue三者的运行机制,这三个是一体的,缺一不可。下面来介绍下这三者的工作原理。

消息队列的工作原理

MessageQueue 是以单链表的数据结构来存储消息的单元,主要包含两个操作:插入和读取,读取又伴随着删除操作。

插入对应enqueueMessage()方法,这个方法的作用是往消息队列中插入一条消息。

读取对应next()方法,这个方法是从MessageQueue中读取一条消息并将其从消息队列删除。如果有新消息,next()方法就会返回这条消息给 Looper 并将其从消息队列中移除,如果消息队列中没有消息,next()就会一直阻塞在那里。

Looper的工作原理

Looper扮演着消息循环的角色,它会无限循环的查看MessageQueue中是否有新消息,有新消息就处理,没有就阻塞。

源码中 Looper 的构造函数:

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

在 Looper 的构造函数会创建一个消息队列,所以LooperMessageQueue是一对一的关系。

Looper 的构造函数是private的,不能在外部直接 new,Handler 的运行必须要有 Looper,那么如何创建 Looper 呢?

Looper为我们提供了prepare()方法,源码如下:

/** Initialize the current thread as a looper.
  + This gives you a chance to create handlers that then reference
  + this looper, before actually starting the loop. Be sure to call
  + {@link #loop()} after calling this method, and end it by calling
  + {@link #quit()}.
  */
public static void prepare() {
    prepare(true);
}

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

prepare的源码很简单,先是调用new Looper(quitAllowed)方法构造Looper,然后把这个Looper对象保存到ThreadLocal中,在其他地方可以通过这个ThreadLocal的get方法来取得这个Looper对象。

创建Looper后,再通过loop方法来开启消息循环,只有调用了looper方法,消息循环系统才会起作用。

看下looper方法的源码:

/**
 *Run the message queue in this thread. Be sure to call
 *{@link #quit()} to end the loop.
 */
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
        Printer logging = me.mLogging;
        if (logging != null) {
            logging.println(">>>>> Dispatching to " + msg.target + " " +
                    msg.callback + ": " + msg.what);
        }

        msg.target.dispatchMessage(msg);

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

loop的源码可以看出:它是一个死循环,他内部调用的是MessageQueuenext()方法。当next()返回新消息,Looper 就会处理此消息:

msg.target.dispatchMessage(msg)

msg.target指得是发送该消息的 Handler 对象,而dispatchMessage运行在创建 Handler 的 Looper 所在的线程,即消息的处理是在 Looper 所在的线程。

MessageQueue 的 next() 方法没消息时就会一直阻塞在那里,导致 loop() 方法也一直阻塞在那里,这样子线程就会一直处于等待状态。

我们可以看到注释里有这么一句话:

Be sure to call {@link #quit()} to end the loop`.
// 要我们确保调用了 quit() 方法来结束 loop。

Looper提供了两个退出循环的方法:

/**
 *Quits the looper.
 */
public void quit() {
    mQueue.quit(false);
}

/**
 * Quits the looper safely.
 */
public void quitSafely() {
    mQueue.quit(true);
}

这两个方法最终调用的时 MessageQueue 里的quit()方法,MessageQueue 的 quit() 方法通知消息队列退出,当消息队列被标记为退出状态时,next()方法就会返回null,从源码中可以看到跳出loop循环的唯一方法是 MessageQueue 的 next() 方法返回null,这样 Looper 就退出了,线程就会立刻终止。

这两个方法的区别是:quit()直接退出,quitSaftely()把消息队列里的消息都处理完毕后在安全的退出。

Handler的工作原理

Handler通过post的一系列方法发送Runnable对象,或通过send的一系列方法发送Message对象,post 方法最终调用的还是 send 方法:

public final boolean post(Runnable r) {
   return  sendMessageDelayed(getPostMessage(r), 0);
}

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

由源码可以看到,使用 post 方法发送 Runnable 或 send 方法发送 Message 对象,最终是调用是 MessageQueue 的 enqueueMessage() 方法向 MessageQueue 中插入消息,所以 post 或 send 系列方法只是向 MessageQueue 中插入一条消息。

MessageQueue 的 next() 方法发现有新消息,取出来交给 Looper 处理, Looper 又把消息交给 Handler 的 dispatchMessage() 处理,看下 dispatchMessage() 方法:

/**
 * Handle system messages here.
 */
public void dispatchMessage(Message msg) {
    if (msg.callback != null) {
        handleCallback(msg);
    } else {
        if (mCallback != null) {
            if (mCallback.handleMessage(msg)) {
                return;
            }
        }
        handleMessage(msg);
    }
}

首先是判断msg.callback,这个 msg.callback 指的时 post 方法所发送的 Runnable 对象,如果不为 null 就执行 handleCallback(msg) 方法,这个方法很简单,就是执行传入的 Runnable 的 run 方法。

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

然后判断 mCallback ,如果不为 null, 就调用mCallback.handleMessage(msg)处理消息, mCallback 是个 Handler.Callback 对象,Handler.Callback是个接口:

/**
 * Callback interface you can use when instantiating a Handler to avoid
 * having to implement your own subclass of Handler.
 *
 * @param msg A {@link android.os.Message Message} object
 * @return True if no further handling is desired
 */
public interface Callback {
    public boolean handleMessage(Message msg);
}

我们可以实现这个接口,然后以Handler handler = new Handler(callback)这种方式来创建 Handler 对象,这个的作用是可以创建一个 Handler 的实例,但不需要派生一个Handler子类并重写其 handleMessage() 方法。

最后调用Handler的 handleMessage() 方法,也就是我们在代码中复写的那个 handleMessage() 方法。

Handler还有一个特殊的构造方法:

/**
 * Use the provided {@link Looper} instead of the default one.
 *
 * @param looper The looper, must not be null.
 */
public Handler(Looper looper) {
    this(looper, null, false);
}

这个构造函数的作用是创建一个指定Looper的Handler实例。我们可以在子线程中创建一个这样的实例:

Handler handler = new Handler(Looper.getMainLooper());

Looper.getMainLooper()返回的时主线程的Looper,这样的Handler可以实现在在子线程中发送消息,在主线程中处理,因为前面提到过:消息处理是在Looper所在的线程。

总结:

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

推荐阅读更多精彩内容