Android消息机制 Handler

在Android中解决子线程更新UI的三种方法:

  • Activity中 调用 runOnUiThread(Runnable action) {}
    源码解析:

    /**
         * Runs the specified action on the UI thread. If the current thread is the UI
         * thread, then the action is executed immediately. If the current thread is
         * not the UI thread, the action is posted to the event queue of the UI thread.
         *
         * @param action the action to run on the UI thread
         */
        public final void runOnUiThread(Runnable action) {
            if (Thread.currentThread() != mUiThread) {
                mHandler.post(action);
            } else {
                action.run();
            }
        }
    
  • View 调用 View.post(Runnable action) {}
    源码解析:

        /**
         * <p>Causes the Runnable to be added to the message queue.
         * The runnable will be run on the user interface thread.</p>
         *
         * @param action The Runnable that will be executed.
         *
         * @return Returns true if the Runnable was successfully placed in to the
         *         message queue.  Returns false on failure, usually because the
         *         looper processing the message queue is exiting.
         *
         * @see #postDelayed
         * @see #removeCallbacks
         */
        public boolean post(Runnable action) {
            final AttachInfo attachInfo = mAttachInfo;
            if (attachInfo != null) {
                return attachInfo.mHandler.post(action);
            }
    
            // Postpone the runnable until we know on which thread it needs to run.
            // Assume that the runnable will be successfully placed after attach.
            getRunQueue().post(action);
            return true;
        }
    
  • 传统的用法: handler.post()
    源码解析:

    /**
         * Causes the Runnable r to be added to the message queue.
         * The runnable will be run on the thread to which this handler is 
         * attached. 
         *  
         * @param r The Runnable that will be executed.
         * 
         * @return Returns true if the Runnable was successfully placed in to the 
         *         message queue.  Returns false on failure, usually because the
         *         looper processing the message queue is exiting.
         */
        public final boolean post(Runnable r)
        {
           return  sendMessageDelayed(getPostMessage(r), 0);
        }
    

    这三种方法最后都殊途同归的调用了 handler.post(Runnable r). 而 handler.post 内部却调用的是 sendMessageDelayed(Message m , 0);

    所以最终的结论引入了 Handler 消息传播机制。

Handler.post(Runnbale r) 的调用

首先查看 post 源码

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

调用到 sendMessageDelayed 方法

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

延时发送消息,其实就是定时发送消息 sendMessageAtTime

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

最后执行到 MessageQueue 轮循消息

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

引发的一些问题:

  • Handler Looper Message MessageQueue 怎么发生联系?
  • Looper是什么?
  • Looper 和 MessageQueue 的关系?
  • Handler 会发生内存泄露?为什么?

在handler创建的时候,handler 和 Looper 产生联系: handler 的构造函数如下:

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

public Handler(Callback callback, boolean async) {
    if (FIND_POTENTIAL_LEAKS) {
        final Class<? extends Handler> klass = getClass();
        if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&
                (klass.getModifiers() & Modifier.STATIC) == 0) {
            Log.w(TAG, "The following Handler class should be static or leaks might occur: " +
                klass.getCanonicalName());
        }
    }

    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创建的时候,和handler所在线程的 looper 产生了关联。在主线程中,Activity在创建的时候就帮我们创建了 looper 和 handler ,所以在子线程中更新ui的前两种方法可以行得通。第三种更新方式,实际原理和前两种一样,只不过是手动在主线程中创建了handler.

注意: 因此在子线程中创建 handler 时候会报错,只有开启了 looper 才可以创建 handler

Looper相关知识点

  1. Looper类用来为一个线程开启一个消息循环
    默认情况下android中新诞生的线程是没有开启消息循环的。(主线程除外,主线程系统会自动为其创建Looper对象,开启消息循环。)
    Looper对象通过MessageQueue来存放消息和事件。一个线程只能有一个Looper,对应一个MessageQueue。

  2. 通常是通过Handler对象来与 looper 进行交互的。
    Handler可看做是Looper的一个接口,用来向指定的Looper发送消息及定义处理方法。
    默认情况下Handler会与其被定义时所在线程的Looper绑定,比如,Handler在主线程中定义,那么它是与主线程的Looper绑定。
    mainHandler = new Handler() 等价于new Handler(Looper.myLooper()).
    Looper.myLooper():获取当前进程的looper对象,类似的 Looper.getMainLooper() 用于获取主线程的Looper对象。

  3. 在非主线程中直接new Handler() 会报如下的错误:
    E/AndroidRuntime( 6173): Uncaught handler: thread Thread-8 exiting due to uncaught exception
    E/AndroidRuntime( 6173): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
    原因是非主线程中默认没有创建Looper对象,需要先调用Looper.prepare()启用Looper。

  4. Looper.loop(); 让Looper开始工作,从消息队列里取消息,处理消息。

    注意:写在Looper.loop()之后的代码不会被执行,这个函数内部应该是一个循环,当调用mHandler.getLooper().quit()后,loop才会中止,其后的代码才能得以运行。

  5. 通过以上知识,可实现主线程给子线程(非主线程)发送消息。

Looper的使用过程以及和 Messagequeue 关系的建立:

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


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

Looper的调用方法是 Looper.prepare() -- new handler()-- looper.loop();

轮询器在循环执行 Messagequeue 中的消息时候调用的:

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
        final Printer logging = me.mLogging;
        if (logging != null) {
            logging.println(">>>>> Dispatching to " + msg.target + " " +
                    msg.callback + ": " + msg.what);
        }

        final long traceTag = me.mTraceTag;
        if (traceTag != 0) {
            Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
        }
        try {
            msg.target.dispatchMessage(msg);
        } finally {
            if (traceTag != 0) {
                Trace.traceEnd(traceTag);
            }
        }

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

当执行到其中的一条message时候, 会回调携带 message 的handler 的方法 dispatchMessage

msg.target.dispatchMessage(msg);

而在 Handler的 dispatchMessage(msg) 中又执行了 callback.handleMessage(msg),

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

在callback的handleMessage(msg)中又接着执行了 handler 的hanleMessage(msg) 方法;

/**
 * Subclasses must implement this to receive messages.
 */
public void handleMessage(Message msg) {
}
    

因此在创建 handler 的时候,一定要复写其中的 handleMessage 方法.

总结

  1. 首先Looper.prepare() 在本线程创建并保存一个实例,然后该Loop实例创建并维护一个 MessageQueue 对象,因为一个线程中 Looper.prepare()只能执行一次,因此 MessageQueue 只会存在一个。

  2. Looper.loop() 会让当前线程进入一个无限循环,不断从消息队列中读取消息,并处理,此时会回调 msg.target.dispatchMessage(msg)

  3. handler 的构造方法会得到当前线程中保存的 looper 实例。

  4. Handler 的 sendMessage() 方法会给msg的 target 赋值为 handler 本身,然后加入到消息队列中。

  5. 在构造 handler 时候,我们会重写 handlemessage() 方法,也是 msg.target.dispatchMessage(msg)最终调用的方法。

三者的关系如下面这个丑图:

网上这个美图更漂亮一些:

补充

  1. 为什么主线程中的Looper.loop() 一直无限循环不会造成 ANR?

答: ANR 的原因就是有需要处理的事情未处理,或者在规定时间内未处理!
因为Android是由事件驱动的,looper.loop()不断地接收事件、处理事件,每一个点击、触摸等等都在主线程looper.loop()的控制之下,如果它停止了,应用也就停止了。只能说对消息的处理阻塞了主线程的looper.loop() 才会导致 ANR, looper.loop()会阻塞自己的运行???

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

推荐阅读更多精彩内容