Andorid异步处理之Handler消息机制分析

Andorid异步处理之Handler消息机制分析
在学习Handler需要明白一下几个问题:
(1)为什么要使用Handler?
(2)为什么不能在线程中更新UI?
(3)Handler如何实现从子线程到主线程的切换(这里其实是涉及到java内存模型中多线程共享堆内存)
(4)Looper中的死循环为什么不会引起ANR,会消耗大量资源吗
(5)主线程的消息循环机制是什么(死循环如何处理其它事务)?
(6)ActivityThread 的动力是什么?(ActivityThread执行Looper的线程是什么)
(7)如何处理Handler 使用不当导致的内存泄露?
(8)子线程有哪些更新UI的方法。
(9)ThreadLocal的作用是什么?

一、Handler基础
        通常我们的耗时操作会在子线程中执行,比如访问网络或者文件操作或者数据库操作,而在耗时任务执行完毕后,如果我们需要跟新UI,则需要在主线程中更新UI,此时需要Handler来处理,Handler可以实现从子线程到主线程的切换。
        Handler的消息机制由五部分组成,Message,MessageQueue,Looper,Handler,和ThreadLocal。如果理解了这五个部分,那么Handler消息机制也就明白了。接下来详细讲一下。
1、Message
       Message翻译过来就是消息,而它就是在线程之间传递到消息。可以携带少量的数据,what,arg1,arg2,obj。这里我们分析一下message的源码;

public final class Message implements Parcelable {
    /**
     * User-defined message code so that the recipient can identify
     * what this message is about. Each {@link Handler} has its own name-space
     * for message codes, so you do not need to worry about yours conflicting
     * with other handlers.
     */
    public int what;

    /**
     * arg1 and arg2 are lower-cost alternatives to using
     * {@link #setData(Bundle) setData()} if you only need to store a
     * few integer values.
     */
    public int arg1;

    /**
     * arg1 and arg2 are lower-cost alternatives to using
     * {@link #setData(Bundle) setData()} if you only need to store a
     * few integer values.
     */
    public int arg2;

    /**
     * An arbitrary object to send to the recipient.  When using
     * {@link Messenger} to send the message across processes this can only
     * be non-null if it contains a Parcelable of a framework class (not one
     * implemented by the application).   For other data transfer use
     * {@link #setData}.
     *
     * <p>Note that Parcelable objects here are not supported prior to
     * the {@link android.os.Build.VERSION_CODES#FROYO} release.
     */
    public Object obj;

    /**
     * Optional Messenger where replies to this message can be sent.  The
     * semantics of exactly how this is used are up to the sender and
     * receiver.
     */
    public Messenger replyTo;

    /**
     * Optional field indicating the uid that sent the message.  This is
     * only valid for messages posted by a {@link Messenger}; otherwise,
     * it will be -1.
     */
    public int sendingUid = -1;

    /** If set message is in use.
     * This flag is set when the message is enqueued and remains set while it
     * is delivered and afterwards when it is recycled.  The flag is only cleared
     * when a new message is created or obtained since that is the only time that
     * applications are allowed to modify the contents of the message.
     *
     * It is an error to attempt to enqueue or recycle a message that is already in use.
     */
    /*package*/ static final int FLAG_IN_USE = 1 << 0;

    /** If set message is asynchronous */
    /*package*/ static final int FLAG_ASYNCHRONOUS = 1 << 1;

    /** Flags to clear in the copyFrom method */
    /*package*/ static final int FLAGS_TO_CLEAR_ON_COPY_FROM = FLAG_IN_USE;

    /*package*/ int flags;

    /*package*/ long when;

    /*package*/ Bundle data;

    /*package*/ Handler target;

    /*package*/ Runnable callback;

    // sometimes we store linked lists of these things
    /*package*/ Message next;

    private static final Object sPoolSync = new Object();
    private static Message sPool;
    private static int sPoolSize = 0;

    private static final int MAX_POOL_SIZE = 50;

    private static boolean gCheckRecycle = true;
这里Message具体的方法我们就忽略了,主要分析几个很重要的参数,对于理解后面的消息队列有很大的帮助。
(1)携带数据
    public int what;
    public int arg1;
    public int arg2;
    public Object obj;
    public Messenger replyTo;用于Messenger跨进程通信
(2) Message next;
        这里会有一个Message next的参数,其实属于链表的话就会很敏感的发现,就是指向它的下一个元素
(3)Handler target;
    这里的target就是指发送该Message的Handler


2、Handler
       Handler的作用就是用来发送和接收数据。
       通过sendXXX来发送数据。在接收消息则是在handleMessage()方法中进行处理。
        首先我们通过Handler mainHandler = new Handler()创建一个Handler实例,那么我们找到Handler的构造方法
public Handler() {
    this(null, false);
}
可以看到调用的是Handler(Callback callback,booolean async)

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;
}
可以看到这里mLooper = Looper.myLooper();这里通过myLooper()调用ThreadLocal.get()获取线程的Looper,ThreadLocal具体后面会讲到。接下来

if (mLooper == null) {
    throw new RuntimeException(
        "Can't create handler inside thread that has not called Looper.prepare()");
}

这里也就说明了为什么在子线程里使用Handler需要先创建Looper。继续往下看mQueue = mLooper.mQueue;这里通过实例化的Looper获取到了消息队列,可以看到拿到的是Looper的mQueue。

接下来我们发送消息,比如sendEmptyMessage()

public final boolean sendEmptyMessage(int what)
{
return sendEmptyMessageDelayed(what0);
}


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


public final boolean sendMessageDelayed(Message msg, long delayMillis)
{
if (delayMillis < 0) {
delayMillis = 0;
}
return sendMessageAtTime(msgSystemClock.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(queuemsguptimeMillis);
}

可以看到最后实际上调用了sendMessageAtTime(),在这个方法里,我们最终调用了MessageQueue的enqueueMessage(queue, msg, uptimeMillis);方法,把Message插入到消息队列中。

3、Message Queue
        消息队列。用于存放所有通过Handler发送的消息,也就是存放的是Message。MessageQueue以队列的形式对外提供了插入和删除 方法(先进先出),虽然说是以队列的形式,但是其实内部是单链表。为什么说是单链表呢?
        其实前面我们分析了Message的参数,其中一个参数就是Message next,也就是指定它指向的下一个元素。
        插入:enqueueMessage(Message msg, long when)
                    将消息插入队列中。

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;
}
这里可以看到在发送消息时,最后调用的是MessageQueue的enqueueMessage()方法,那么具体是怎么插入的呢,看这段代码 
             prev = p;
             p = p.next;
             msg.next = p; // invariant: p == prev.next
             prev.next = msg;


        删除:next()
                    就是将消息读取,并从队列中删除。这里的next()执行的是一个无限循环的方法,如果队列中没有消息,就会处于阻塞状态。有新消息时,next()方法就会立即返回这条消息。并从单链表中移除。具体代码如下:

Message next() {
    // 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();
        }

        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) {
                // 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);
                    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;
    }
}
通过源码可以看到,在next()方法中有一个 for (;;)来实现死循环,并返回新的Message,同时从链表中删除这个消息代码如下:
      
            if (prevMsg != null) {
                        prevMsg.next = msg.next;
                    } else {
                        mMessages = msg.next;
                    }
                    msg.next = null;

此外,一个线程中只会有一个MessageQueue。这一点从插入和读取消息的方法中synchronized (this)就可以看出。
4、Looper
        轮询器/消息泵/循环,Looper有一个looper()方法,在该方法中是一个死循环,会不断轮询MessageQueue, 当发现MessageQueue中有新消息时,就会传递到Handler的handleMessage()方法中,如果没有新消息,则处于阻塞状态。
        (1)Looper的构造方法

    private Looper(boolean quitAllowed) {
        mQueue = new MessageQueue(quitAllowed);
        mThread = Thread.currentThread();
    }
            Looper在创建时,就会创建一个消息队列,同时会保存Looper对象所在的线程。而Handler在创建对象时,所在的线程里必须已经实例化了Looper,否则会报错Can't create handler inside thread that has not called Looper.prepare()")。
        (2)UI线程的Looper
           线程默认是没有Looper,因此在线程中实例化Handler,则需要先创建Looper,调用Looper.prepare(),实例化Handler再调用Looper.loop(),开始轮询。但是UI线程我们并没有看到创建Looper。其实是因为在UI线程创建时就已经创建了Looper,因此不需要我们手动创建。
        (3)Looper中的ThreadLocal
                ThreadLocal的作用其实就是帮助Handler获取当前线程的Looper

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

    // 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 slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;

        final long traceTag = me.mTraceTag;
        if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
            Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
        }
        final long start = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
        final long end;
        try {
            msg.target.dispatchMessage(msg);
            end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
        } finally {
            if (traceTag != 0) {
                Trace.traceEnd(traceTag);
            }
        }
        if (slowDispatchThresholdMs > 0) {
            final long time = end - start;
            if (time > slowDispatchThresholdMs) {
                Slog.w(TAG, "Dispatch took " + time + "ms on "
                        + Thread.currentThread().getName() + ", h=" +
                        msg.target + " cb=" + msg.callback + " msg=" + msg.what);
            }
        }

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

这里可以看到,也是利用for(;;)来执行死循环,在MessageQueue的next()方法得到新消息后,则loop()方法则会调用  msg.target.dispatchMessage(msg);其中msg.target就是Handler对象,而
dispatchMessage()方法接下来会调用Handler的handleMessage()方法。


5、ThreadLocal
       TheadLocal是JAVA提供的用于在线程内部获取数据的存储类。具体如下:
    
public class ThreadLocal<T> {

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

public void set(T value) {
    Thread t = Thread.currentThread();
    ThreadLocalMap map = getMap(t);
    if (map != null)
        map.set(this, value);
    else
        createMap(t, value);
}

static class ThreadLocalMap {
}
}
可以看出,在TheadLocal有一个静态内部类是ThreadLocalMap,就是一个用来保存数据的类。同时在ThreadLocal中提供了一个set()方法,用来存储数据,而get()方法则用来获取保存的数据。那么接下来回到Looper。

public final class Looper {
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
private static Looper sMainLooper;  // guarded by Looper.class

final MessageQueue mQueue;
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));
}

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

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 slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;

        final long traceTag = me.mTraceTag;
        if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
            Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
        }
        final long start = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
        final long end;
        try {
            msg.target.dispatchMessage(msg);
            end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
        } finally {
            if (traceTag != 0) {
                Trace.traceEnd(traceTag);
            }
        }
        if (slowDispatchThresholdMs > 0) {
            final long time = end - start;
            if (time > slowDispatchThresholdMs) {
                Slog.w(TAG, "Dispatch took " + time + "ms on "
                        + Thread.currentThread().getName() + ", h=" +
                        msg.target + " cb=" + msg.callback + " msg=" + msg.what);
            }
        }

        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();
    }
}
分析Looper源码,可以看到初始化变量时有一个static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();也就是说明了在ThreadLocal保存的就是当前线程的Looper
接下来在prepare方法中会创建当前线程的looper,并通过ThreadLocal中的set方法sThreadLocal.set(new Looper(quitAllowed));
将创建的looper对象保存起来。
而在调用Looper的loop()方法进行轮询时,我们分析loop()方法,可以看到   final Looper me = myLooper();而myLooper()方法中return sThreadLocal.get();返回了我们之前保存的looper对象,因此保证了轮询的就是我们当前的线程的looper对象。之后在死循环中,通过looper对象拿到MessageQueue中的消息。再通过 msg.target.dispatchMessage(msg);将消息分发给msg.target,也就是发送消息的Handler,再dispatchMessage会调用handlerMessage()从而就可以处理消息了。

二、重要问题
        在从源码角度分析了Handler机制后,现在我们来回到之前提到的问题。
(1)为什么要使用Handler?为什么不能在线程中更新UI?
           在线程中更新UI的问题,就要从UI的设计的设计角度来讲,android中设计的UI是单线程模型的,因为如果改为多线程的话线程同步和线程安全问题将会很麻烦,因此就设计为单线程模型。但是是不是可以考虑加锁来解决多线程的问题呢?加锁会有以下两个问题:
            首先加上锁机制会让UI访问的逻辑变得复杂
            锁机制会降低UI访问的效率,因为锁机制会阻塞某些线程的执行。
            也正因为在非UI线程中无法更新UI,因此才会设计一个Handler
(2)为什么Handler可以实现线程的切换
          首先假设在A线程创建Handler,同时调用Looper.prepare()创建Looper对象和MessageQueue对象。之后开启一个线程B发送消息,那么调用handler.sendMessage()其实就是调用handler对应的线程中的MessageQueue插入一个消息,之后轮询器looper会轮询这个消息,并调用msg.target.dispatchMessage(),也就是handler的dispatchMessage(),此时就是在B线程中调用A中handler对象方法。在这个方法中会回调handlerMessage()方法。
        当然最根本的原因是我们创建的Handler保存在堆中,是可以线程共享的,然后才有上面分析。
(3)Looper中的死循环为什么不会引起ANR,会消耗大量资源吗
            不会,因为从上面loop方法可以看出,有消息时会处理,没有消息时会阻塞





        

猜你喜欢

转载自blog.csdn.net/ckq5254/article/details/79954781
今日推荐