Adnroid源码学习笔记:Handler 线程间通讯

常见的使用Handler线程间通讯:

//主线程:
Handler handler = new Handler() {
@Override
    public void handleMessage(Message msg) {
        ...
    }
};

//子线程:
Message message = new Message();  
message.arg1 = 1;  
Bundle bundle = new Bundle();  
bundle.putString("test", "test");  
message.setData(bundle);  
handler.sendMessage(message); 

这类操作一般用于在子线程更新UI。在主线程创建一个handler,重写handlermessage方法,然后在子线程里发送消息,主线程里就会接受到消息。这就是简单的线程间通讯。

如果在子线程创建handler对象则会报错。根据Log提示,子线程创建handler需要调用Looper.prepare() (在main函数中已经调用了Looper.prepareMainLooper(),该方法内会调起Looper.prepare()),Looper.loop()方法 。但是即使子线程调用Looper.prepare()创建Looper对象,这个Looper也是子线程的,不可以用于更新UI操作。

那到底Handler、Looper这几个类之间是如何工作的呢?我们从源头看起,以下是Looper类的prepare()方法:

public final class Looper { 
    ...
    final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>(); //threadLocal是线程内部的数据存储类,该类存储了线程的所有数据信息。

    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)); //创建一个Looper(Looper的构造器里也创建了一个MessageQueue,),将Looper与线程关联起来
    }

    public static @Nullable Looper myLooper() { //下面会看到的,设置Handler类里的Looper时会调用该方法
        return sThreadLocal.get(); //获得Looper对象
    }
    ...
}

当handler传输message时,不论是调用sendMessage(Message msg)还是sendMessageDelayed(),最后都会指向sendMessageAtTime()方法:

public class Handler {    
    ...
    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);
    }
    ...
}

mQueue即消息队列,用于将收到的消息以队列形式排列,提供出队和入队方法,该变量是Looper的成员变量,在Handler创建时赋值给handler

public class Handler {
    ...
    final Looper mLooper;
    final MessageQueue mQueue;
    mLooper = Looper.myLooper();  //创建Handler前调用Looper.prepare()时定义并设置了Looper,这里调用Looper.myLooper()来获得该Looper
    mQueue = mLooper.mQueue;
    ...
}

上面调用的enqueueMessage(queue, msg, uptimeMillis)方法作用是消息入队

private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
    msg.target = this; //把handler本身赋值给要入队的消息,用来待会儿出队使用
    if (mAsynchronous) {
        msg.setAsynchronous(true);
    }
    return queue.enqueueMessage(msg, uptimeMillis);
}

可以看到最后是由消息队列queue调用自身MessageQueue类的入队方法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;
}

mMessages是MessageQueue类的一个成员变量,用以记录排在最前面的消息,msg是我们传入的message,msg.next是Message类的成员变量,可以理解成下一条消息。入列方法重点看这几句:

Message p = mMessages;
msg.next = p;  //把mMessages赋值给新入队的这条消息的next
mMessages = msg;  //把新入队的消息赋值给mMessages

就像排队一样,msg是来插队的,排第一的mMessages自愿排到msg的后面,并让msg站到自己原来的位置上,这样就完成的msg的入队操作,整个消息入队操作是按照时间来排序的。至于出队操作,就在一开始所提到的ActivityTread中的main方法里调用的Looper.loop()方法里:

public static void loop() {
    ...

    for (;;) {
        ...
        Message msg = queue.next(); //获取下一条消息
        ...
        msg.target.dispatchMessage(msg); //传递消息
        ...
        msg.recycleUnchecked(); //清空状态,循环往复
        }
    }
    ...
}

提炼出来就是在loop方法里一直死循环,从MessageQueue消息队列里使用next()方法获得下一条消息,next方法简单看就是:

Message msg = mMessages;
mMessages = msg.next;
msg.next = null;
return msg;

这就是简单的解释消息出列,把排第一的消息作为方法的返回值,然后让排第二的排到第一去。获得消息后使用msg.target(上面入队时赋值的handler)来传递消息:

public void dispatchMessage(Message msg) {
    if (msg.callback != null) {
        handleCallback(msg); //如果有callback参数则调用处理回调的方法
    } else {
        if (mCallback != null) {
            if (mCallback.handleMessage(msg)) {
                return;
            }
        }
        handleMessage(msg); //将消息作为参数传递出去
    }
}

至此,handler传递消息的整个流程走完。另外还有一个我们经常用到handler的方法post:

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

private static Message getPostMessage(Runnable r) { //将runnable变成message自身的callback变量
    Message m = Message.obtain();
    m.callback = r;
    return m;
}

可以看到,post的runnable参数经过getPostMessage()方法最后被赋值给要传递下去的消息的callback这个变量,等到消息出列时,如果消息带有callback参数则调用处理回调的方法handleCallback(msg)

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

可以看到,不论是从sendMessage里发出的消息,还是在post传递的runnable里执行的代码,最后都是殊途同归,都是在UI线程运行的。最后总结一下吧,线程间通讯原理大概就是:

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

推荐阅读更多精彩内容