handler学习笔记

1、ActivityThread:在Android中它就代表了Android的主线程,注意是代表而不是说它就是一个Thread类

这里,我们主要看main方法中的Looper相关的,其他的先忽略(注:不同版本的API对应的源码,会有点区别,但是关键地方一样,不用纠结这个,这里的ActivityThread,是API 26的)

    public static final void main(String[] args) {

        .....

        Looper.prepareMainLooper();

        ActivityThread thread = new ActivityThread();
        thread.attach(false);

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

        .....

    }

2、主线程中的handler,可以处理系统级别的handler消息,其中包括:处理4大组件中的切换、通信、甚至处理返回键、Activity的启动模式、杀死进程等等

3、handler的创建

import android.os.Handler;
import android.os.Message;

private Handler mHandler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
    }
};

4、消息的创建

import android.os.Message

Message m= Message.obtain();

obtain()对应源码:

/**
* Return a new Message instance from the global pool. Allows us to
* avoid allocating new objects in many cases.
*/
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();
}

5、handler的使用过程中,Message的回收
一个Message(消息)被创建出来后,会被handler发送到到MessageQueue中,MessageQueue存在于Looper中

5.1、在使用Message的时候,我们从来没有关心过Message的回收,其实,也不用关心。系统会自动回收的。因为不可能在Message一被创建(放在MessageQueue中还未被使用)或从MessageQueue刚取出还没处理就回收,所有,直接去看Looper中的loop()。(即:Looper.loop();)

5.2、loop()对应源码

    /**
     * Run the message queue in this thread. Be sure to call
     * {@link #quit()} to end the loop.
     */
    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();
        }
    }

说明:
s1、for(;;)中Message msg = queue.next();不断的从MessageQueue(消息队列)中取消息,如果是空,就return;for循环这里,是对消息的轮询

s2、对于说明1中的空情况,我们可能会有疑问:什么时候会为空呢?
在ActivityThread中:

扫描二维码关注公众号,回复: 2525370 查看本文章
public void handleMessage(Message msg) {
    switch (msg.what) {
    ......
    }
}

有一种情况:

case EXIT_APPLICATION:
    if (mInitialApplication != null) {
        mInitialApplication.onTerminate();
    }
    Looper.myLooper().quit();
    break;

再看Looper中的quit()
其中:MessageQueue mQueue

    /**
     * Quits the looper.
     * <p>
     * Causes the {@link #loop} method to terminate without processing any
     * more messages in the message queue.
     * </p><p>
     * Any attempt to post messages to the queue after the looper is asked to quit will fail.
     * For example, the {@link Handler#sendMessage(Message)} method will return false.
     * </p><p class="note">
     * Using this method may be unsafe because some messages may not be delivered
     * before the looper terminates.  Consider using {@link #quitSafely} instead to ensure
     * that all pending work is completed in an orderly manner.
     * </p>
     *
     * @see #quitSafely
     */
    public void quit() {
        mQueue.quit(false);
    }

继续看MessageQueue中的quit方法

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

其中:
removeAllFutureMessagesLocked()对应源码为:

    private void removeAllFutureMessagesLocked() {
        final long now = SystemClock.uptimeMillis();
        Message p = mMessages;
        if (p != null) {
            if (p.when > now) {
                removeAllMessagesLocked();
            } else {
                Message n;
                for (;;) {
                    n = p.next;
                    if (n == null) {
                        return;
                    }
                    if (n.when > now) {
                        break;
                    }
                    p = n;
                }
                p.next = null;
                do {
                    p = n;
                    n = p.next;
                    p.recycleUnchecked();
                } while (n != null);
            }
        }
    }

removeAllMessagesLocked()对应源码:

    private void removeAllMessagesLocked() {
        Message p = mMessages;
        while (p != null) {
            Message n = p.next;
            p.recycleUnchecked();
            p = n;
        }
        mMessages = null;
    }

这样看,就清楚了:用户退出程序的时候,MessageQueue清空消息,Looper中的循环loop取到空消息,在没有任何消息的情况下,loop会return

s3、注意一句话

msg.target.dispatchMessage(msg);

这里,是对消息的处理

msg.target就是handler,在这里,就是handler的回调
Handler中:

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

s4、继续往下看loop的源码,我们会看到一句话:

msg.recycleUnchecked();

在Message中

    /**
     * Recycles a Message that may be in-use.
     * Used internally by the MessageQueue and Looper when disposing of queued Messages.
     */
    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++;
            }
        }
    }

s5、如果我们自己手动回收呢:代码如下:

 private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {

            switch (msg.what) {
                case 100:

                    //do something...

                    msg.recycle();

                    break;
            }
        }
    };

看看recycle的源码:

    /**
     * Return a Message instance to the global pool.
     * <p>
     * You MUST NOT touch the Message after calling this function because it has
     * effectively been freed.  It is an error to recycle a message that is currently
     * enqueued or that is in the process of being delivered to a Handler.
     * </p>
     */
    public void recycle() {
        if (isInUse()) {
            if (gCheckRecycle) {
                throw new IllegalStateException("This message cannot be recycled because it "
                        + "is still in use.");
            }
            return;
        }
        recycleUnchecked();
    }

在结尾处,我们又看到了recycleUnchecked();

总结:在消息池中拿到一个Message,然后被handler放到消息队列中,Looper通过loop()(依赖其中的for循环),检查有没有消息,没有就return;有消息,就处理,处理完以后,Message自己会调用方法回收。不用我们自己手动回收。

如果我们自己在处理完消息后,在handleMessage中自己回收了(见上面的说明5),不为错,也证明思路严谨,但是,因为message自己会回收,所有在结果一样的情况下,反而会因为自己的收到回收,多消耗一点内存(因为回收了2次。虽然这个消耗的内存,可以忽略不计,可是,毕竟对结果没有任何影响)。

6、handler的移除
在用Activity的时候,在onDestroy方法中,建议加上消息的移除
例如,在Activity中,用handler发了消息100,

 @Override
    protected void onDestroy() {
        if (handler != null && handler.hasMessages(100)) {
            handler.removeMessages(100);
        }
        super.onDestroy();
    }

handler中

   /**
     * Remove any pending posts of messages with code 'what' that are in the
     * message queue.
     */
    public final void removeMessages(int what) {
        mQueue.removeMessages(this, what, null);
    }

MessageQueue中

void removeMessages(Handler h, int what, Object object) {
        if (h == null) {
            return;
        }

        synchronized (this) {
            Message p = mMessages;

            // Remove all messages at front.
            while (p != null && p.target == h && p.what == what
                   && (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 && n.what == what
                        && (object == null || n.obj == object)) {
                        Message nn = n.next;
                        n.recycleUnchecked();
                        p.next = nn;
                        continue;
                    }
                }
                p = n;
            }
        }
    }

猜你喜欢

转载自blog.csdn.net/u014620028/article/details/78319074