Skip to content

Latest commit

 

History

History
934 lines (765 loc) · 35.7 KB

2.Android线程间通信之Handler消息机制.md

File metadata and controls

934 lines (765 loc) · 35.7 KB

2.Android线程间通信之Handler消息机制

Binder/Socket用于进程间通信,而Handler消息机制用于同进程的线程间通信,Handler消息机制是由一组MessageQueue、Message、Looper、Handler共同组成的,为了方便且称之为Handler消息机制。

有人可能会疑惑,为何Binder/Socket用于进程间通信,能否用于线程间通信呢?答案是肯定,对于两个具有独立地址空间的进程通信都可以,当然也能用于共享内存空间的两个线程间通信,这就好比杀鸡用牛刀。接着可能还有人会疑惑,那handler消息机制能否用于进程间通信?答案是不能,Handler只能用于共享内存地址空间的两个线程间通信,即同进程的两个线程间通信。很多时候,Handler是工作线程向UI主线程发送消息,即App应用中只有主线程能更新UI,其他工作线程往往是完成相应工作后,通过Handler告知主线程需要做出相应地UI更新操作,Handler分发相应的消息给UI主线程去完成,如下图:

img

由于工作线程与主线程共享地址空间,即Handler实例对象mHandler位于线程间共享的内存堆上,工作线程与主线程都能直接使用该对象,只需要注意多线程的同步问题。工作线程通过mHandler向其成员变量MessageQueue中添加新Message,主线程一直处于loop()方法内,当收到新的Message时按照一定规则分发给相应的handleMessage()方法来处理。所以说,Handler消息机制用于同进程的线程间通信,其核心是线程间共享内存空间,而不同进程拥有不同的地址空间,也就不能用handler来实现进程间通信

消息机制主要包含:

  • Message:消息分为硬件产生的消息(如按钮、触摸)和软件生成的消息;Message中有一个用于处理消息的Handler;
  • MessageQueue:消息队列的主要功能向消息池投递消息(MessageQueue.enqueueMessage)和取走消息池的消息(MessageQueue.next);MessageQueue有一组待处理的Message;
  • Handler:消息辅助类,主要功能向消息池发送各种消息事件(Handler.sendMessage)和处理相应消息事件(Handler.handleMessage);Handler中有Looper和MessageQueue的成员变量。
  • Looper:不断循环执行(Looper.loop),按分发机制将消息分发给目标处理者。Looper有一个MessageQueue消息队列;

handle_msg_arch

首先想一想平时我们是怎么使用的:

private Handler mHandler = new Handler(new Handler.Callback() {
    @Override
    public boolean handleMessage(@NonNull Message msg) {
        // xxxx.
        return false;
    }
});

mHandler.sendMessage(msg);

所以这里分析还是要从Handler开始,主要看它的构造函数和sendMessage()方法:

1. Handler构造函数

final Looper mLooper;
final MessageQueue mQueue;
@UnsupportedAppUsage
final Callback mCallback;
final boolean mAsynchronous;
@UnsupportedAppUsage
IMessenger mMessenger;

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

public Handler(@Nullable Callback callback) {
    this(callback, false);
}
// 可以设置Looper进来
public Handler(@NonNull Looper looper) {
    this(looper, null, false);
}

public Handler(@Nullable Callback callback, boolean async) {
    // 匿名类、内部类和本地类都必须申请为static,否则会警告可能出现内存泄露
    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());
        }
    }
    // 1. 如果不设置Looper对象进来,Looper会通过Looper.myLooper()获取Looper对象
    mLooper = Looper.myLooper();
    if (mLooper == null) {
        throw new RuntimeException(
            "Can't create handler inside thread " + Thread.currentThread()
                    + " that has not called Looper.prepare()");
    }
    // 获取Looper中的MessageQueue赋值给当前的MessageQueue变量
    mQueue = mLooper.mQueue;
    // 回调接口
    mCallback = callback;
    // 设置消息是否为异步处理方式,默认都是同步的
    // If true, the handler calls {@link Message#setAsynchronous(boolean)} for
    // each {@link Message} that is sent to it or {@link Runnable} that is posted to it.
    // 如果是异步的会调用Message的setAsynchronous方法,然后在MessageQueue中会判断是不是异步的消息
    mAsynchronous = async;
}

上面看到会通过Looper类的myLooper()获取Looper对象

// sThreadLocal.get() will return null unless you've called prepare().
@UnsupportedAppUsage
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();

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

/**
 * Return the {@link MessageQueue} object associated with the current
 * thread.  This must be called from a thread running a Looper, or a
 * NullPointerException will be thrown.
 */
public static @NonNull MessageQueue myQueue() {
    return myLooper().mQueue;
}

上面注释写的很明白:除非你调用了prepare()方法,不然sThreadLocal.get()会返回null。那sThreadLocal是啥? prepare()方法又是干啥的?这里还是分两步:

sThreadLocal

ThreadLocal:线程本地存储区(Thread Local Storage,简称为TLS),每个线程都有自己的私有的本地存储区域,不同线程之间彼此不能访问对方的TLS区域。TLS常用的操作方法:

  • ThreadLocal.set(T value):将value存储到当前线程的TLS区域:

    public void set(T value) {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);
    }
  • ThreadLocal.get():获取当前线程TLS区域的数据:

    public T get() {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null) {
            ThreadLocalMap.Entry e = map.getEntry(this);
            if (e != null) {
                @SuppressWarnings("unchecked")
                T result = (T)e.value;
                return result;
            }
        }
        return setInitialValue();
    }

而sThreadLocal就是线程本地存储变量,它的意义就是在本线程内的任何对象内保持一致。

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

final MessageQueue mQueue;
final Thread mThread;
private Looper(boolean quitAllowed) {
    // 创建MessageQueue,并将quitAllowed传入MessageQueue的构造函数
    mQueue = new MessageQueue(quitAllowed);
    // 保存当前的线程
    mThread = Thread.currentThread();
}

从代码上可以看到prepare()方法的作用是创建一个Looper对象,然后将该Looper对象保存到sThreadLocal中。也就是说,prepare函数通过ThreadLocal机制,巧妙地把Looper和调用prepare的线程(也就是最终的处理线程)绑定在一起了。当事件源向这个Looper发送消息的时候,其实是把消息加到这个Looper的消息队列里了。那么,该消息就将由和Looper绑定的处理线程来处理。

这里有点麻烦了,我们上面使用的代码中并没有调用Looper.prepare()方法啊,理论上这里应该是null,Handler是无法使用的,为什么我们还能正常使用Handler?Looper.prepare()究竟是什么时候调用的?那我们需要看一下prepare()和prepare(boolean quitAllowed)方法都有哪些地方调用了:

/**
* Initialize the current thread as a looper, marking it as an
* application's main looper. The main looper for your application
* is created by the Android environment, so you should never need
* to call this function yourself.  See also: {@link #prepare()}
*/
public static void prepareMainLooper() {
    prepare(false);
    synchronized (Looper.class) {
        if (sMainLooper != null) {
            throw new IllegalStateException("The main Looper has already been prepared.");
        }
        sMainLooper = myLooper();
    }
}

发现在Looper类中有个prepareMainLooper()的方法,注释上面写的也比较清楚,说这是Android运行环境创建的应用程序的主looper,你不能自己调用这个方法,那我们看一下这个方法是从哪里调用的,ActivityThread类中的main函数,看到这个main函数,就知道这个类不简单啊:

/**
 * This manages the execution of the main thread in an
 * application process, scheduling and executing activities,
 * broadcasts, and other operations on it as the activity
 * manager requests.
 *
 * {@hide}
 */
public final class ActivityThread extends ClientTransactionHandler {
    // ....
        public static void main(String[] args) {
        Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");

        // Install selective syscall interception
        AndroidOs.install();

        // CloseGuard defaults to true and can be quite spammy.  We
        // disable it here, but selectively enable it later (via
        // StrictMode) on debug builds, but using DropBox, not logs.
        CloseGuard.setEnabled(false);

        Environment.initForCurrentUser();

        // Make sure TrustedCertificateStore looks in the right place for CA certificates
        final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
        TrustedCertificateStore.setDefaultUserDirectory(configDir);

        Process.setArgV0("<pre-initialized>");
		// 调用Looper.prepareMainLooper()方法
        Looper.prepareMainLooper();

        // Find the value for {@link #PROC_START_SEQ_IDENT} if provided on the command line.
        // It will be in the format "seq=114"
        long startSeq = 0;
        if (args != null) {
            for (int i = args.length - 1; i >= 0; --i) {
                if (args[i] != null && args[i].startsWith(PROC_START_SEQ_IDENT)) {
                    startSeq = Long.parseLong(
                            args[i].substring(PROC_START_SEQ_IDENT.length()));
                }
            }
        }
        ActivityThread thread = new ActivityThread();
        thread.attach(false, startSeq);

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

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

        // End of event ActivityThreadMain.
        Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
        // Looper.loop()启动
        Looper.loop();

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

从上面ActivityThread类的注释中可以看到说ActivityThread是应用程序的主线程。ActivityThread类是Android APP进程的初始类,它的main函数是这个APP进程的入口。

ActivityThread类的详细介绍可以参考这篇文章,这里就不细说ActivityThread类了,我们只需要知道Android运行环境会启动ActivityThread类,他是主线程,而ActivityThread类中的main函数会调用Looper.prepareMainLooper()和Looper.loop()方法。

到这里梳理一下上面的TODO:

  1. Looper类构造函数创建MessageQueue
  2. ActivityThread调用了Looper.prepareMainLooper()后又调用了Looper.loop()方法,要分析Looper.loop()方法的实现。

MessageQueue的实现

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

public final class MessageQueue {
    private final boolean mQuitAllowed;
    private long mPtr; // used by native code
    // Message中的next指向了下一个Message
    Message mMessages;
    private boolean mBlocked;
    
    MessageQueue(boolean quitAllowed) {
        mQuitAllowed = quitAllowed;
        mPtr = nativeInit();
    }
    
    private native static long nativeInit();
    private native static void nativeDestroy(long ptr);
    @UnsupportedAppUsage
    private native void nativePollOnce(long ptr, int timeoutMillis); /*non-static for callbacks*/
    private native static void nativeWake(long ptr);
    private native static boolean nativeIsPolling(long ptr);
    private native static void nativeSetFileDescriptorEvents(long ptr, int fd, int events);
}    

MessageQueue中有一个native的方法;

  • nativeInit()
    • 创建了NativeMessageQueue对象,增加其引用计数,并将NativeMessageQueue指针mPtr保存在Java层的MessageQueue
    • 创建了Native Looper对象
    • 调用epoll的epoll_create()/epoll_ctl()来完成对mWakeEventFd和mRequests的可读事件监听
  • nativeDestroy()方法
    • 调用RefBase::decStrong()来减少对象的引用计数
    • 当引用计数为0时,则删除NativeMessageQueue对象
  • nativePollOnce
    • 调用Looper::pollOnce()来完成,空闲时停留在epoll_wait()方法,用于等待事件发生或者超时
  • nativeWake
    • 调用Looper::wake()来完成,向管道mWakeEventfd写入字符;

Looper.loop()方法:

/**
* Run the message queue in this thread. Be sure to call
* {@link #quit()} to end the loop.
*/
public static void loop() {
    // 从sThreadLocal获取当前的Looper
    final Looper me = myLooper();
    if (me == null) {
        throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
    }
    // 获取当前Looper的MessageQueue
    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();

    // Allow overriding a threshold with a system prop. e.g.
    // adb shell 'setprop log.looper.1000.main.slow 1 && stop && start'
    final int thresholdOverride =
        SystemProperties.getInt("log.looper."
                                + Process.myUid() + "."
                                + Thread.currentThread().getName()
                                + ".slow", 0);

    boolean slowDeliveryDetected = false;
	// 不断去循环执行
    for (;;) {
        // 去MessageQueue中的下一个Message,可能会堵塞
        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);
        }

        try {
            // 分发Message,Message.target是Message中保存的当前handler对象,这里相对于调用Handler的dispatchMessage(msg)方法
            msg.target.dispatchMessage(msg);
            if (observer != null) {
                observer.messageDispatched(token, msg);
            }
            dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
        } catch (Exception exception) {
            if (observer != null) {
                observer.dispatchingThrewException(token, msg, exception);
            }
            throw exception;
        } finally {
            ThreadLocalWorkSource.restore(origWorkSource);
            if (traceTag != 0) {
                Trace.traceEnd(traceTag);
            }
        }
        // 恢复调用者信息
        // Make sure that during the course of dispatching the
        // identity of the thread wasn't corrupted.
        final long newIdent = Binder.clearCallingIdentity();
        // 将Message放入消息池
        msg.recycleUnchecked();
    }
}

// Looper的quit方法是调用MessageQueue.quit()方法
public void quit() {
    mQueue.quit(false);
}


public void quitSafely() {
    mQueue.quit(true);
}

loop()进入循环模式,不断重复下面的操作,直到没有消息时退出循环

  • 读取MessageQueue的下一条Message;
  • 把Message分发给相应的target;
  • 再把分发后的Message回收到消息池,以便重复利用。

Message类

这里我们需要看一下Message类中的target及recycleUncheked()方法:

public final class Message implements Parcelable {
    // 消息类别
    public int what;
    // 参数1
    public int arg1;
    // 参数2
    public int arg2;
    // 消息内容
    public Object obj;
    // 消息响应方Handler
    /*package*/ Handler target;
    // 维护下一个消息
    /*package*/ Message next;
    // 消息的回调方法
    /*package*/ Runnable callback;
    public static final Object sPoolSync = new Object();
    // sPool也是Message对象,
    private static Message sPool;
    private static int sPoolSize = 0;

    private static final int MAX_POOL_SIZE = 50;
    
    public static Message obtain(Handler h) {
        Message m = obtain();
        // 将handler赋值给target保存
        m.target = h;

        return m;
    }
    
    public void recycle() {
        if (isInUse()) {
            if (gCheckRecycle) {
                throw new IllegalStateException("This message cannot be recycled because it "
                        + "is still in use.");
            }
            return;
        }
        recycleUnchecked();
    }
    
    void recycleUnchecked() {
        // Mark the message as in use while it remains in the recycled object pool.
        // Clear out all other details.
        flags = FLAG_IN_USE;
        what = 0;
        arg1 = 0;
        arg2 = 0;
        obj = null;
        replyTo = null;
        sendingUid = UID_NONE;
        workSourceUid = UID_NONE;
        when = 0;
        target = null;
        callback = null;
        data = null;

        synchronized (sPoolSync) {
            // 如果当前消息池小于最大的数量限制,就把消息放到消息池中
            if (sPoolSize < MAX_POOL_SIZE) {
                next = sPool;
                // 把新放入的Message加到链表的表头
                sPool = this;
                sPoolSize++;
            }
        }
    }   
}    

2. Handler.sendMessage(Message)和dispatchMessage(Message)方法

public void handleMessage(@NonNull Message msg) {
}

/**
 * Handle system messages here.
 */
public void dispatchMessage(@NonNull Message msg) {
    if (msg.callback != null) {
        // 如果Message存在回调方法,就回调Message.callback.run()方法
        handleCallback(msg);
    } else {
        if (mCallback != null) {
            // 如果Message没有回调方法,而Handler对象中设置了Callback接口,这里就回调Callback.handleMessage(msg)方法
            if (mCallback.handleMessage(msg)) {
                return;
            }
        }
        // handler自己的handleMessage方法,默认空实现,子类可重写该方法
        handleMessage(msg);
    }
}

public final boolean sendEmptyMessageDelayed(int what, long delayMillis) {
    Message msg = Message.obtain();
    msg.what = what;
    return sendMessageDelayed(msg, delayMillis);
}

private static Message getPostMessage(Runnable r) {
    Message m = Message.obtain();
    m.callback = r;
    return m;
}

public final void removeCallbacksAndMessages(@Nullable Object token) {
    mQueue.removeCallbacksAndMessages(this, token);
}
postAtFrontOfQueue():将消息插入到队列头部

通过调用sendMessageAtFrontOfQueue计入一个when为0的message到队列,即插入到队列的头部。可以尽量保证快速执行。

MessageQueue类的常用方法

MessageQueue非常重要,因为quit、next等都最终调用的是MessageQueue类:

public final class MessageQueue {
    private final boolean mQuitAllowed;
    private long mPtr; // used by native code
    // 消息在MessageQueue中使用Message表示,而Message包含一个next变量,该变量指向下一个消息
    // 所以队列中的消息以链表的结构进行保存
    Message mMessages;

    // 获取MessageQueue的下一个Message
    Message next() {
        // 如果MessageQueue已退出就直接返回
        // Return here if the message loop has already quit and been disposed.
        // This can happen if the application tries to restart a looper after quit
        // which is not supported.
        final long ptr = mPtr;
        if (ptr == 0) {
            return null;
        }

        int pendingIdleHandlerCount = -1; // -1 only during first iteration
        int nextPollTimeoutMillis = 0;
        for (;;) {
            if (nextPollTimeoutMillis != 0) {
                Binder.flushPendingCommands();
            }
            // 该方法的作用是从消息队列中取出一个消息。MessageQueue中没有保存消息队列,真正的消息队列在JNI的C代码中
            // 也就是在C环境中创建了一个NativeMessageQueue数据对象。该方法的第一个参数是int型变量,在C环境中该变量
            // 会被强制转换为一个NativeMessageQueue对象。如果消息队列中没消息,当前线程会被挂起。
            // 堵塞操作,当等待nextPollTimeoutMillis时长或消息队列别唤醒,都会返回
            // nextPollTimeoutMillis代表下一个消息到来前,还需要等待的时长;当nextPollTimeoutMillis = -1时,表示消息队列中无消息,会一直等待下去。
            nativePollOnce(ptr, nextPollTimeoutMillis);

            synchronized (this) {
                // Try to retrieve the next message.  Return if found.
                final long now = SystemClock.uptimeMillis();
                Message prevMsg = null;
                Message msg = mMessages;
               
                if (msg != null && msg.target == null) {
                    // 当当前的消息的Handler为空时,就查询异步消息
                    // Stalled by a barrier.  Find the next asynchronous message in the queue.
                    do {
                        prevMsg = msg;
                        msg = msg.next;
                    } while (msg != null && !msg.isAsynchronous());
                }
                if (msg != null) {
                    // 仅仅是为了判断消息所指定的执行时间是否到了,如果到了就返回该消息
                    if (now < msg.when) {
                        // Next message is not ready.  Set a timeout to wake up when it is ready.
                        nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
                    } else {
                        // Got a message.
                        mBlocked = false;
                        if (prevMsg != null) {
                            prevMsg.next = msg.next;
                        } else {
                            mMessages = msg.next;
                        }
                        msg.next = null;
                        if (DEBUG) Log.v(TAG, "Returning message: " + msg);
                        // 设置消息的使用状态,即FLOAG_IN_USE的flag
                        msg.markInUse();
                        return msg;
                    }
                } else {
                    // No more messages.
                    nextPollTimeoutMillis = -1;
                }

                // Process the quit message now that all pending messages have been handled.
                if (mQuitting) {
                    dispose();
                    return null;
                }

                // If first time idle, then get the number of idlers to run.
                // Idle handles only run if the queue is empty or if the first message
                // in the queue (possibly a barrier) is due to be handled in the future.
                if (pendingIdleHandlerCount < 0
                        && (mMessages == null || now < mMessages.when)) {
                    pendingIdleHandlerCount = mIdleHandlers.size();
                }
                if (pendingIdleHandlerCount <= 0) {
                    // No idle handlers to run.  Loop and wait some more.
                    mBlocked = true;
                    continue;
                }

                if (mPendingIdleHandlers == null) {
                    mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)];
                }
                mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers);
            }
            // 空闲回调函数
            // Run the idle handlers.
            // We only ever reach this code block during the first iteration.
            for (int i = 0; i < pendingIdleHandlerCount; i++) {
                final IdleHandler idler = mPendingIdleHandlers[i];
                mPendingIdleHandlers[i] = null; // release the reference to the handler

                boolean keep = false;
                try {
                    keep = idler.queueIdle();
                } catch (Throwable t) {
                    Log.wtf(TAG, "IdleHandler threw exception", t);
                }

                if (!keep) {
                    synchronized (this) {
                        mIdleHandlers.remove(idler);
                    }
                }
            }

            // Reset the idle handler count to 0 so we do not run them again.
            pendingIdleHandlerCount = 0;

            // While calling an idle handler, a new message could have been delivered
            // so go back and look again for a pending message without waiting.
            nextPollTimeoutMillis = 0;
        }
    }
    
    // 添加一条消息到消息队列
    boolean enqueueMessage(Message msg, long when) {
        // 每条消息必须有一个target
        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) {
                // 内部会将mMessages消息添加到C环境中的消息队列中,并且如果消息线程正处于挂起状态,则唤醒该线程
                nativeWake(mPtr);
            }
        }
        return true;
    }

    

    void quit(boolean safe) {
        if (!mQuitAllowed) {
            throw new IllegalStateException("Main thread not allowed to quit.");
        }

        synchronized (this) {
            if (mQuitting) {
                return;
            }
            mQuitting = true;

            if (safe) {
                removeAllFutureMessagesLocked();
            } else {
                removeAllMessagesLocked();
            }

            // We can assume mPtr != 0 because mQuitting was previously false.
            nativeWake(mPtr);
        }
    }

    // 清除所有的message
    private void removeAllMessagesLocked() {
        Message p = mMessages;
        while (p != null) {
            Message n = p.next;
            p.recycleUnchecked();
            p = n;
        }
        mMessages = null;
    }

    void removeCallbacksAndMessages(Handler h, Object object) {
        if (h == null) {
            return;
        }

        synchronized (this) {
            Message p = mMessages;
            // 从消息队列的头开始,移除所有符合条件的消息
            // Remove all messages at front.
            while (p != null && p.target == h
                   && (object == null || p.obj == object)) {
                Message n = p.next;
                mMessages = n;
                p.recycleUnchecked();
                p = n;
            }
            // 移除剩余符合条件的消息
            // Remove all messages after front.
            while (p != null) {
                Message n = p.next;
                if (n != null) {
                    if (n.target == h && (object == null || n.obj == object)) {
                        Message nn = n.next;
                        n.recycleUnchecked();
                        p.next = nn;
                        continue;
                    }
                }
                p = n;
            }
        }
    }

根据前面的分析可知,Handler中的消息队列实际就是某个Looper的消息队列,那么,Handler如此安排的目的何在? 在回答这个问题之前,我先来问一个问题:怎么往Looper的消息队列插入消息?如果不知道Handler,这里有一个很原始的方法可解决上面这个问题:

  • 调用Looper的myQueue,它将返回消息队列对象MessageQueue。
  • 构造一个Message,填充它的成员,尤其是target变量。
  • 调用MessageQueue的enqueueMessage,将消息插入消息队列。 这种原始方法的确很麻烦,且极容易出错。但有了Handler后,我们的工作就变得异常简单了。Handler更像一个辅助类,帮助我们简化编程的工作。

Handler内存泄露

有关内存泄露请猛戳内存泄露

在上面分析Handler类源码时,其构造函数中第一部分的代码就是 匿名类、内部类和本地类都必须申请为static,否则会警告可能出现内存泄露。那为什么会导致内存泄露呢?

Handler mHandler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        // do something.
    }
}

当我们这样创建Handler的时候Android Lint会提示我们这样一个warning: In Android, Handler classes should be static or leaks might occur.
一直以来没有仔细的去分析泄露的原因,先把主要原因列一下:

  • Android程序第一次创建的时候,默认会创建一个Looper对象,Looper去处理Message Queue中的每个Message,主线程的Looper存在整个应用程序的生命周期.
  • Hanlder在主线程创建时会关联到LooperMessage Queue,Message添加到消息队列中的时候Message(排队的Message)会持有当前Handler引用, 当Looper处理到当前消息的时候,会调用Handler#handleMessage(Message).就是说在Looper处理这个Message之前, 会有一条链MessageQueue -> Message -> Handler -> Activity,由于它的引用导致你的Activity被持有引用而无法被回收
  • 在java中,no-static的内部类会隐式的持有当前类的一个引用。static的内部类则没有。

具体分析

public class SampleActivity extends Activity {

    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            // do something
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 发送一个10分钟后执行的一个消息
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() { }
        }, 600000);

        // 结束当前的Activity
        finish();
    }
}

finish()的时候,该Message还没有被处理,Message持有Handler,Handler持有Activity,这样会导致该Activity不会被回收,就发生了内存泄露.

解决方法

  • 通过程序逻辑来进行保护。

    • 如果Handler中执行的是耗时的操作,在关闭Activity的时候停掉你的后台线程。线程停掉了,就相当于切断了Handler和外部连接的线, Activity自然会在合适的时候被回收。
    • 如果Handler是被delayMessage持有了引用,那么在ActivityonDestroy()方法要调用Handlerremove*方法,把消息对象从消息队列移除就行了。
      • 关于Handler.remove*方法
        • removeCallbacks(Runnable r) ——清除r匹配上的Message。
        • removeCallbacks(Runnable r, Object token) ——清除r匹配且匹配token(Message.obj)的Message,token为空时,只匹配r。
        • removeCallbacksAndMessages(Object token) ——清除所有callback以及token匹配上的Message,如果token是null就会清楚所有callback和message。我们更多需要的是清除以该Handlertarget的所有Message(Callback)就调用如下方法即可handler.removeCallbacksAndMessages(null);
        • removeMessages(int what) ——按what来匹配
        • removeMessages(int what, Object object) ——按what来匹配
  • Handler声明为静态类。 静态类不持有外部类的对象,所以你的Activity可以随意被回收。但是不持有Activity的引用,如何去操作Activity中的一些对象? 这里要用到弱引用

public class MyActivity extends Activity {
	private MyHandler mHandler;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mHandler = new MyHandler(this);
	}

	@Override
	protected void onDestroy() {
		// Remove all Runnable and Message.
		mHandler.removeCallbacksAndMessages(null);
		super.onDestroy();
	}

	static class MyHandler extends Handler {
		// WeakReference to the outer class's instance.
		private WeakReference<MyActivity> mOuter;

		public MyHandler(MyActivity activity) {
			mOuter = new WeakReference<MyActivity>(activity);
		}

		@Override
		public void handleMessage(Message msg) {
			MyActivity outer = mOuter.get();
			if (outer != null) {
				// Do something with outer as your wish.
			}
		}
	}
}