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) {}
    源码解析:

        /**
         * 

    Causes the Runnable to be added to the message queue. * The runnable will be run on the user interface thread.

    * * @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 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)最终调用的方法。

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

Android消息机制 Handler_第1张图片

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

Android消息机制 Handler_第2张图片

补充

  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

你可能感兴趣的:(Android消息机制 Handler)