关于Looper,Handler,Message, MessageQueue,ThreadLocal的一些分析

ThreadLocal:实现线程的本地存储,每个线程都拥有属于自己的数据,只有本线程才可以获得自身存储的数据。但实际上存储数据的是ThreadLocal中的静态内部类Values。每个Thread中都持有一个ThreadLocal.Values。对数据的存储和取出都是通过ThreadLocal。
这里讲一下个人对于Thread,ThreadLocal,ThreadLocal.Values的理解。

  1. 通过对ThreadLocal的操控,取出Thread中的ThreadLocal.Values localValues,如果localValues为空,立刻初始化,再调用Values的put方法,将ThreadLocal中的reference作为键,把要存储的数据存入Values;
  2. ThreadLocal持有某种要存储的类型数据,一旦初始化ThreadLocal后,其实每个Thread都默认拥有了该类型数据。因为一旦初始化ThreadLocal后,其拥有的一个私有变量hash就会自增。而Values其实是将数据存入数组table,数组的索引是以hash为基础的;
  3. ThreadLocal的值在table数组中的存储位置总是为ThreadLocal的reference字段所标识的对象的下一个位置。比如索引是index,reference的存储位置是index,ThreadLocal的值存储位置为index + 1;

首先ThreadLocal的全局变量

    private final Reference<ThreadLocal<T>> reference
            = new WeakReference<ThreadLocal<T>>(this);

    private static AtomicInteger hashCounter = new AtomicInteger(0);

    private final int hash = hashCounter.getAndAdd(0x61c88647 * 2);

接下来看一下ThreadLocal中的set方法

 public void set(T value) {
        Thread currentThread = Thread.currentThread();
        Values values = values(currentThread);
        if (values == null) {
            values = initializeValues(currentThread);
        }
        values.put(this, value);
    }
    Values values(Thread current) {
        return current.localValues;
    }
    Values initializeValues(Thread current) {
        return current.localValues = new Values();
    }
 Values() {
            initializeTable(INITIAL_SIZE);
            this.size = 0;
            this.tombstones = 0;
        }
       private void initializeTable(int capacity) {
            this.table = new Object[capacity * 2];
            this.mask = table.length - 1;
            this.clean = 0;
            this.maximumLoad = capacity * 2 / 3; // 2/3
        }

我们要存储的数据就在table中,table的默认大小为32(INITIAL_SIZE=16;)

接下来看一下Values的put方法。

  void put(ThreadLocal<?> key, Object value) {
            cleanUp();//当ThreadLocal被垃圾回收时,清理掉

            // Keep track of first tombstone. That's where we want to go back
            // and add an entry if necessary.
            int firstTombstone = -1;

            for (int index = key.hash & mask;; index = next(index)) {
                Object k = table[index];

                if (k == key.reference) {
                    // Replace existing entry.
                    table[index + 1] = value;
                    return;
                }

                if (k == null) {
                    if (firstTombstone == -1) {
                        // Fill in null slot.
                        table[index] = key.reference;
                        table[index + 1] = value;
                        size++;
                        return;
                    }

                    // Go back and replace first tombstone.
                    table[firstTombstone] = key.reference;
                    table[firstTombstone + 1] = value;
                    tombstones--;
                    size++;
                    return;
                }

                // Remember first tombstone.
                if (firstTombstone == -1 && k == TOMBSTONE) {
                    firstTombstone = index;
                }
            }
        }

接下来看一下ThreadLocal的put方法.

 public T get() {
        // Optimized for the fast path.
        Thread currentThread = Thread.currentThread();
        Values values = values(currentThread);
        if (values != null) {
            Object[] table = values.table;
            int index = hash & values.mask;
            if (this.reference == table[index]) {
                return (T) table[index + 1];
            }
        } else {
            values = initializeValues(currentThread);
        }

        return (T) values.getAfterMiss(this);
    }

当想取出的数据是null时,会调用values.getAfterMiss(this),这个函数返回的值取决于ThreadLocal的initialValue:

   protected T initialValue() {
        return null;
    }

在返回null前,Values会刷新一次table中与ThreadLocal.reference对应的值(这里只列出部分代码)

 Object getAfterMiss(ThreadLocal<?> key) {
            Object[] table = this.table;
            int index = key.hash & mask;

            // If the first slot is empty, the search is over.
            if (table[index] == null) {
                Object value = key.initialValue();

                // If the table is still the same and the slot is still empty...
                if (this.table == table && table[index] == null) {
                    table[index] = key.reference;
                    table[index + 1] = value;
                    size++;

                    cleanUp();
                    return value;
                }
                .
                .
                .


我们一般在子线程中使用Handler的方法是

 class LooperThread extends Thread {
 public Handler mHandler;

  public void run() {
          Looper.prepare();

            mHandler = new Handler() {
                public void handleMessage(Message msg) {
                    // process incoming messages here
                }
            };

            Looper.loop();
        }

先看一下Looper的全局变量

    // sThreadLocal.get() will return null unless you've called prepare().
    static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
    private static Looper sMainLooper;  // guarded by Looper.class

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

quitAllowed是标志该线程的Looper是否被允许中断。默认是true。这里可以很明显看出来ThreadLocal存储了每一个线程的Looper。

Looper的初始化

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

MessageQueue是在Looper中被初始化,而且一个Looper对应一个MessageQueue和一个Thread。可以通过myQueue获取对应于Looper的MessageQueue。
Looper除了提供prepare方法外,还提供了prepareMainLooper方法,该方法是给ActivityThread创建Looper使用的。我们可以通过getMainLooper获取主线程的Looper。
Looper是可以退出的:quit和quitSafely。这两个方法相同的地方都是调用MessageQueue的quit,不同的地方是quit会直接退出Looper,quitSafely会将消息队列中的消息处理完毕后退出(此处的消息不包括pending delayed messages,除非调用quitSafely时刚好该消息开始调用。)退出后如果想再次使用可以调用loop。

loop方法

  public static void loop() {
        final Looper me = myLooper();//从ThreadLocal中取出looper
        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
            //当调用Looper.quit时,queue.next会返回null
            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
            Printer logging = me.mLogging;
            if (logging != null) {
                logging.println(">>>>> Dispatching to " + msg.target + " " +
                        msg.callback + ": " + msg.what);
            }

            msg.target.dispatchMessage(msg);//此处的target是handler

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


Handler的工作主要有两方面:一个是安排Message和Runnable在某个时间点执行,主要通过post, postAtTime, postDelayed, sendEmptyMessage, sendMessage, sendMessageAtTime, sendMessageDelayed,另一个是处理消息。
Handler的初始化有多种,不过大同小异,可以归纳为两类,主要区别在于是否将Looper赋予给Handler。默认情况下是Handler调用myLooper获取Looper。

    final MessageQueue mQueue;
    final Looper mLooper;
    final Callback mCallback;
    final boolean mAsynchronous;

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

    public Handler(Looper looper, Callback callback, boolean async) {
        mLooper = looper;
        mQueue = looper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }

其中mAsynchronized是标志message同步或异步,true为异步。 当设为true时,handler会为每一个message或runnable调用setAsynchronous。这里可以看到Looper一定要在Handler初始化之前调用,不然会抛出错误。

Handler可以调用obtainMessage获取Message,同时会将自身传递给Message.target。不过在最后将消息插入MessageQueue时还会有一次将Handler传递给Message。

    public final Message obtainMessage(int what, int arg1, int arg2, Object obj){
        return Message.obtain(this, what, arg1, arg2, obj);
    }

接下来看一下发送消息。实际上post方法最后会通过send方法来实现。

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

    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只是往MessageQueue插入消息。
再来看下Looper.loop中对message.target调用dispatchMessage的具体实现

    public void dispatchMessage(Message msg) {
    /*
    检查Message的callback是否为空,这里的callback实际上Handler的post方法传递的Runnable参数。
    callback为空时检查Handler的mCallback 是否为空。看回构造函数,可以发现对mCallback的赋值。当为空时最后调用Handler的handleMessage方法。
    这里可以发现我们其实不必使用以下方法创建Handler的实例
            mHandler = new Handler() {
                public void handleMessage(Message msg) {
                    // process incoming messages here
                }
            };
    而是采用这种方法:Handler handler = new Handler(callback);
    */
        if (msg.callback != null) {
            handleCallback(msg);
        } else {
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            handleMessage(msg);
        }
    }

    private static void handleCallback(Message message) {
        message.callback.run();
    }

    public interface Callback {
        public boolean handleMessage(Message msg);
    }


MessageQueue虽然被称为消息队列,但它内部其实维护了一个链表.调用Looper.myQueue可以获得对应的MessageQueue。
我们先来看一下MessageQueue中的变量。


    private final boolean mQuitAllowed;//判断Looper是否允许被退出

    @SuppressWarnings("unused")
    private long mPtr; // used by native code

    Message mMessages;//链表头
    private final ArrayList<IdleHandler> mIdleHandlers = new ArrayList<IdleHandler>();//用于存放IidleHandler
    private IdleHandler[] mPendingIdleHandlers;
    private boolean mQuitting;//判断Looper是否已经停止
    private boolean mBlocked;//判断next()是否堵塞

    // The next barrier token.
    // Barriers are indicated by messages with a null target whose arg1 field carries the token.
    private int mNextBarrierToken;//MessageQueue中含有的同步障碍的标签

这里讲解一下IdleHandler。这是一个回调接口,当发现Thread将堵塞等待更多消息时调用。它在MessageQueue中只会执行一次。
这个接口只有一个方法,当MessageQueue为空而且正在等待更多的消息时调用,如果return true,将会让IdleHhandler活跃,return false时,将移除该IdleHandler。当MessageQueue中有延迟执行的Message时,该方法可能被调用。

 /**
     * Callback interface for discovering when a thread is going to block
     * waiting for more messages.
     */
    public static interface IdleHandler {
        /**
         * Called when the message queue has run out of messages and will now
         * wait for more.  Return true to keep your idle handler active, false
         * to have it removed.  This may be called if there are still messages
         * pending in the queue, but they are all scheduled to be dispatched
         * after the current time.
         */
        boolean queueIdle();
    }

添加IdleHandler的方法。当queueIdle方法return false时, 添加的IdleHandler可能会被自动移除。这个方法是线程安全的。

    public void addIdleHandler(@NonNull IdleHandler handler) {
        if (handler == null) {
            throw new NullPointerException("Can't add a null IdleHandler");
        }
        synchronized (this) {
            mIdleHandlers.add(handler);
        }
    }

移除IdleHandler。同样该方法也是线程安全。

    public void removeIdleHandler(@NonNull IdleHandler handler) {
        synchronized (this) {
            mIdleHandlers.remove(handler);
        }
    }

接下来讲解一下enqueueMessage

  boolean enqueueMessage(Message msg, long when) {
        //判断message是否绑定了handler
        if (msg.target == null) {
            throw new IllegalArgumentException("Message must have a target.");
        }
        //判断是否重复使用Message,这意味着你不可以在一个handler里接收message后直接把该message又发往另一个handler。
        if (msg.isInUse()) {
            throw new IllegalStateException(msg + " This message is already in use.");
        }
        //当Looper已经停止后,往MessageQueue中插入消息会抛出错误,并且自动回收Message
        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;
    }

在看next()之前补充一个小小的知识点。当我们想控制部分Message在某个时间点调用,但是又没有办法确定这个具体的时间点,我们可以调用postSyncBarrier。
这个方法会发送一个同步障碍(也就是target为空的message)往MessageQueue,对于消息队列的插入和取出会和往常一样,直到遇上这个障碍。此时,队列中的message,假设并没有调用SetAsynchronous(true){ 也就是Message的flags = FLAG_ASYNCHRONOUS ,这里其实还有另一个方法设置,Handler的构造器中都有boolean async这个参数,实例化时传入true即可。},也就是正常的message,将无法从MessageQueue中被取出。直到我们调用了removeSyncBarrier(token),这个token会在调用postSyncBarrier后返回。
我们看一下postSyncBarrier这个方法

 public int postSyncBarrier() {
        return postSyncBarrier(SystemClock.uptimeMillis());
    }

    private int postSyncBarrier(long when) {
        // Enqueue a new sync barrier token.
        // We don't need to wake the queue because the purpose of a barrier is to stall it.
        synchronized (this) {
            final int token = mNextBarrierToken++;
            final Message msg = Message.obtain();
            msg.markInUse();
            msg.when = when;
            msg.arg1 = token;

            Message prev = null;
            Message p = mMessages;
            if (when != 0) {
                while (p != null && p.when <= when) {
                    prev = p;
                    p = p.next;
                }
            }
            if (prev != null) { // invariant: p == prev.next
                msg.next = p;
                prev.next = msg;
            } else {
                msg.next = p;
                mMessages = msg;
            }
            return token;
        }
    }

这里可以看到,msg的时间是调用该函数的时间,token是mNextBarrierToken。
移除同步障碍的代码:

 public void removeSyncBarrier(int token) {
        // Remove a sync barrier token from the queue.
        // If the queue is no longer stalled by a barrier then wake it.
        synchronized (this) {
            Message prev = null;
            Message p = mMessages;
            //当target不为空而且token不相同时才跳出。p等于空的时候?那是会报错的
            while (p != null && (p.target != null || p.arg1 != token)) {
                prev = p;
                p = p.next;
            }
            if (p == null) {
                throw new IllegalStateException("The specified message queue synchronization "
                        + " barrier token has not been posted or has already been removed.");
            }
            final boolean needWake;
            if (prev != null) {
                prev.next = p.next;
                needWake = false;
            } else {
                mMessages = p.next;
                needWake = mMessages == null || mMessages.target != null;
            }
            p.recycleUnchecked();

            // If the loop is quitting then it is already awake.
            // We can assume mPtr != 0 when mQuitting is false.
            if (needWake && !mQuitting) {
                nativeWake(mPtr);
            }
        }
    }

接下来可以看最关键的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; //空闲的IdlerHandler数量,只有第一次调用时为-1。
        int nextPollTimeoutMillis = 0;//下次轮循的时间
        for (;;) {
            if (nextPollTimeoutMillis != 0) {
                Binder.flushPendingCommands();//如果nextPollTimeoutMmillis不为0,则等待消息
            }

            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;
                /*
                当调用postSyncBarrier后,将会在此处把正常的message拦截,直到遇见调用了setAsnchronous(true)的message或是msg为空才会跳出。
                */
                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;
                }

                // 调用了quit后,next()将返回null,Looper.loop会跳出轮循
                if (mQuitting) {
                    dispose();
                    return null;
                }

                /*
                IdleHandler只有在queue为空或者MessageQueue的第一个Message执行时间未到时调用,并且只会执行一次。
                */
                if (pendingIdleHandlerCount < 0
                        && (mMessages == null || now < mMessages.when)) {
                    pendingIdleHandlerCount = mIdleHandlers.size();
                }

                //当IdleHandler为空时,返回
                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);
                }

                //当queueIdle返回false时,执行remove。
                if (!keep) {
                    synchronized (this) {
                        mIdleHandlers.remove(idler);
                    }
                }
            }

            // 执行完IdlerHandler后将数值设为0,以确保不会再次执行。
            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;
        }
    }


接下来探讨一下Message。先看看他的变量。

    /**
    用于接收者确认消息,每一个handler都有自己的名称空间,因此不用担心handler之间的冲突
    **/
    public int what;

     /**
     当你想存储一些Integer类型的数据时,可以用arg1,arg2代替setData()
     **/
    public int arg1; 
    public int arg2;

    /**
    发送任意一种类型给接收者,当时用Messenger发送时,该类型必须不为空并且实现了Parcelable接口,其他数据的发送可以调用setData。
     */
    public Object obj;

    /**
    可选的Messanger用来确定message发送的地方,具体的方法由接收方和发送方决定
     */
    public Messenger replyTo;

    /**
    可选的域用来确定发送的message的uid。这只在Messenger发送时才有效,其余时期都是-1
     */
    public int sendingUid = -1;

    /** 
    这个标签在message进入队列,发送,回收时设定。标签只在新的message被创建或是程序允许修改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的实例化方法。该方法返回一个全局池中的message实例,允许我们避免多次分配内存。实际message的其余重载方法都是基于该方法,先调用obtain(),再对message的各个参数赋值。message对全局池的构建后文再述。

    public static Message obtain() {
        synchronized (sPoolSync) {
            if (sPool != null) {
                Message m = sPool;
                sPool = m.next;
                m.next = null;
                m.flags = 0; // clear in-use flag
                sPoolSize--;
                return m;
            }
        }
        return new Message();
    }

对message进行回收的方法有两个,一个是recycle,一个是recycleUnchecked。这两个方法的不同之处在于前者在调用时会先检查message的状态参数,当发现flags == FLAG_IN_USE时会抛出错误。而recycleUnchecked可以回收处于FLAG_IN_USE的message,并且该方法是在MessageQueue和Looper释放message时调用。
在Handler,Message,MessageQueue,Looper中,recycle调用的地方有MessageQueue.enqueueMessage(),并且是在Looper调用quit后再次将message入队列时调用。recycleUnchecked调用的地方有Looper.loop(),MessageQueue的enqueueMessage和一系列remove方法。

  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 = -1;
        when = 0;
        target = null;
        callback = null;
        data = null;

        synchronized (sPoolSync) {
            if (sPoolSize < MAX_POOL_SIZE) {
                next = sPool;
                sPool = this;
                sPoolSize++;
            }
        }
    }

注意观察recycleUunchecked,这里会构建一个全局池链表,sPool始终指向链表头。这里其实是一个队列,先进先出,message先入链表头,当需要复用时取出链表头的message。

最后讲一些message中的方法

  • copyFrom(Messsage o):将o的数据赋值给自己。浅拷贝Bundle数据域。不拷贝o的链表字段,时间和回调方法。
  • getWhen():返回Message的发送时间。
  • setTarget(Handler target):设置接收消息的Handler。
  • getTarget:返回Message用于接收消息的Handler
  • getData:返回Message的Bundle对象,可以在需要时延迟初始化,当Bundle未实例化时将其实例化。当需要在进程间通过Messenger传输信息时,你需要为通过Bundle的setClassLoader(CcliassLoader)创建一个类加载器,当你接收到消息时才可以将其实例化。
  • peekData:当Bundle未实例化时返回null,但不会为其延迟初始化。
  • setData:设置一个Bundle对象
  • sendToTarget:调用message的Handler发送消息.

参考:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值