Android Handler 消息机制

Android 应用程序的每一个线程在启动时,都可以首先在内部创建一个消息队列,然后在进行入到一个无限循环中,不断检查它的消息队列是否有新的消息需要处理,如果没有就会进入睡眠等待状态,直到有新的消息需要处理时。Android只允许在主线程操作UI,故常用Handler发送消息给主线程的消息队列来更新UI。

附上自己画的流程图

Handler
一. 创建线程消息队列
  1. Android应用程序的消息队列是使用MessageQueue对象来描述的,可以调用Looper类的静态函数prepare方法来创建。
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方法内部又调用了prepare(true),然后创建了Looper对象,Looper对象内部又创建了MessageQueue对象。另外sThreadLocal.set方法将Looper对象保存在了当前线程局部变量中。Looper.myLooper方法可以该变量

public static @Nullable Looper myLooper() {
        return sThreadLocal.get();
}

2. 主线程的消息队列创建

public static void main(String[] args) {
       
        Looper.prepareMainLooper();

        ActivityThread thread = new ActivityThread();
        thread.attach(false);

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

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

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

ActivityThread的main()方法如上,当前方法是在主线程运行的,在调用Looper.prepareMainLooper()方法时,就会去创建消息队列,并将创建的Looper对象保存在sMainLooper静态变量中

二:线程消息的循环过程

当Android应用程序的消息队列创建好之后,我们就可以调用Looper类的静态成员函数loop使它进入到一个消息循环中

public class Looper{

 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;
        ...
        for (;;) {
            Message msg = queue.next(); // might block
            if (msg == null) {
                // No message indicates that the message queue is quitting.
                return;
            }
        ...
       }
}

myLooper()方法先取出当前线程的消息队列,然后for循坏不断检查这个消息队列。如果当前线程的消息队列为空,那么queue.next()方法会使线程进入睡眠等待的状态。

三. 线程消息的发送过程

1. 创建Handler对象

public Handler() {
        this(null, false);
}

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

Handler无參的构造函数,会调用Looper.myLooper()方法,如果创建Handler所在的线程,还没有创建消息队列的时候,那么该方法就去返回空。

2.消息的发送是使用Handler类的成员函数sendMessage().

public class Handler{
  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的sendMessage()方法首先会取出Handler中构建时MessageQueue对象,然后queue.enqueueMessage()方法会将发送的消息根据消息处理的时间先后顺序插入到MessageQueue里

boolean enqueueMessage(Message msg, long when) {
        if (msg.target == null) {
            throw new IllegalArgumentException("Message must have a target.");
        }
      
        synchronized (this) {
            ...
            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 {
                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;
            }
                if (needWake) {
                nativeWake(mPtr);
            }
        }
        return true;
    }

if (p == null || when == 0 || when < p.when)
a. 如果当前消息是一个空队列,那么 p = mMessages; 也就是p为空的情况。
b. 插入的消息的处理事件等于0,也就是when等于0
c. 插入的消息的处理事件小于消息队列中队头的消息处理事件,这个事件会将needWake 设为true.

上面这三种情况会将当前消息插入mMessages队列的队头,其他情况则是根据消息处理时间插入到mMessages中。

3. needWake处理
needWake为true.那么nativeWake(mPtr)该native方法就会去调用。底层实现是将创建Looper对象的实现,底层会创建一个管道,并利用epoll机制去监听这个管道的读操作符。这里nativeWake()方法正是向这个管道的写描述符写入一个“W”字符,这个时候epoll机制就会去通知由于调用Looper.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;
        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);
                }
            }
            
        }
    }

当线程从 queue.next()方法处唤醒之后,取出消息队列的对头的消息。msg.target是保存了Handler对象的引用。然后调用Handler的dispatchMessage()方法处理消息

五:总结

Android应用程序线程的消息队列,利用c语言底层语言,建立管道,利用epoll机制,与Linux操作系统进行交互,使得线程在消息队列为空的时候进行睡眠等待,等有消息的时候在进行唤醒处理。从而进行页面的绘制,UI方面的处理。故该机制是对于Android系统是非常之重要的。

另外:Handler、Looper、MessageQueue的相对关系?
首先Looper是创建线程的消息队列的,那么对于一个线程来说,只会有一个Looper对象。Looper对象创建时又会创建MessageQueue.

Handler创建时,会拿到当前线程创建的Looper对象。故Handler可以有多个。故多个Handler可以向对应线程的消息队列里面发送消息。

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

推荐阅读更多精彩内容