其他分享
首页 > 其他分享> > Android消息机制分析

Android消息机制分析

作者:互联网

Android消息机制分析

1.Handler的简单用法

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val msg = Message()
        msg.what = 1

        handler.sendMessage(msg)
    }

    private val handler = @SuppressLint("HandlerLeak")
    object:Handler(Looper.getMainLooper()) {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)

            when (msg.what) {
                1 -> Log.d("TAG", "发送消息")
            }
        }
    }
}

2.消息机制流程分析

2.1 Handler,Looper,MessageQueue的创建过程

2.1.1 Handler的构造方法

首先看下Handler的构造方法,有两个构造方法已经废弃掉了。
最后一个构造方法里面会传一个looper,同时获取到looper对应的MessageQueue,还有Callback参数。
不传looper的话,就需要通过Looper.myLooper()去拿looper对象。

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

    @Deprecated
    public Handler(@Nullable Callback callback) {
        this(callback, false);
    }

    public Handler(@NonNull Looper looper) {
        this(looper, null, false);
    }

    public Handler(@Nullable 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 " + Thread.currentThread()
                        + " that has not called Looper.prepare()");
        }
        mQueue = mLooper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }

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

2.1.2 Looper的相关方法

首先通过looper.prepare()方法,初始化looper,
同时通过static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
存储到ThreadLocal的TreadLocalMap中,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();
    }

Thread,ThreadLocal,looper之间的关系是什么,
ThreadLocal可以认为是为线程存储数据准备的,也就是一个线程对应一个looper,线程可以通过ThreadLocal拿到其对应的looper。

线程如何通过ThreadLocal拿到其对应的looper呢。

首先看Looper的prepare方法中,

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

sThreadLocal.set(new Looper(quitAllowed));这一步,进去仔细看下

也就是ThreadLocal的set方法

    public void set(T value) {//value就是对应的new Looper(quitAllowed)
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);//1.先通过getMap方法,拿到ThreadLocalMap
        if (map != null)
            map.set(this, value); //2.将ThreadLocal和new Looper()进行绑定
        else
            createMap(t, value); //3.map为null,创建一个map,同时绑定
    }

    ThreadLocalMap getMap(Thread t) {//getMap方法
        return t.threadLocals;
    }

    void createMap(Thread t, T firstValue) {//创建map的操作
        //创建ThreadLocalMap对象,关联ThreadLocal和Looper。然后将ThreadLocalMap赋值给Thread.threadLocals变量
        t.threadLocals = new ThreadLocalMap(this, firstValue);
    }

    ThreadLocalMap(ThreadLocal<?> firstKey, Object firstValue) {//ThreadLocal构造函数
        table = new Entry[INITIAL_CAPACITY];
        int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);
        table[i] = new Entry(firstKey, firstValue);
        size = 1;
        setThreshold(INITIAL_CAPACITY);
    }

ThreadLocal内部的Entery的数据结构:

    static class ThreadLocalMap {

        /**
         * The entries in this hash map extend WeakReference, using
         * its main ref field as the key (which is always a
         * ThreadLocal object).  Note that null keys (i.e. entry.get()
         * == null) mean that the key is no longer referenced, so the
         * entry can be expunged from table.  Such entries are referred to
         * as "stale entries" in the code that follows.
         */
        static class Entry extends WeakReference<ThreadLocal<?>> {
            /** The value associated with this ThreadLocal. */
            Object value;

            Entry(ThreadLocal<?> k, Object v) {
                super(k);
                value = v;
            }
        }
        //....
    }

所以ThreadLocal内部包含了一个ThreadLocalMap,将当前TheadLocal和new Looper()进行了一个绑定,构造出一个ThreadLocal对象,ThreadLocal为key,looper是value.同时将这个ThreadLocal对象赋值给Thread的threadLocals变量

简单说就是如下一段代码:

Thread().threadLocals = new ThreadLocalMap(Looper().sThreadLocal /*as Key*/, looper /*as Value*/);

用Looper中的sThreadLocal变量作为key,looper作为value构造一个ThreadLocalMap,赋值给Thread的threadLocals变量。

这样线程和looper就对应起来,在Thread中使用Handler的流程首先是
通过Looper.prepare()方法,将Looper.sThreadLocal和Looper以及当前Tread做一个绑定。
这样后面就可以在Thread中通过Looper.myLooper()方法直接拿到对应的looper

获取looper的方法:

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

然后是ThreadLocal的get方法

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

针对主线程创建的looper有如下方法:
可以通过getMainLooper()拿到主线程的looper

   @Deprecated
    public static void prepareMainLooper() {
        prepare(false);
        synchronized (Looper.class) {
            if (sMainLooper != null) {
                throw new IllegalStateException("The main Looper has already been prepared.");
            }
            sMainLooper = myLooper();
        }
    }

    /**
     * Returns the application's main looper, which lives in the main thread of the application.
     */
    public static Looper getMainLooper() {
        synchronized (Looper.class) {
            return sMainLooper;
        }
    }

以上可以说都是准备工作:
明确了,Handler,Looper,MessageQueue,ThreadLocal,Thread之间的关系,这里简单总结一下:

1.首先是Thread和ThreadLocal以及Looper和MessageQueue之间的关系:

->Looper.prepare() //先准备好Looper
Looper looper = new Looper(); 创建looper对象
looper.queue = new MessageQueue(); 创建MessageQueue对象并赋值给looper的queue变量

以looper的sThreadLocal变量为key,looper为value创建ThreadLocal对象赋值给Thread的sThreadLocal变量。
Thread().sThreadLocal = new TreadLocal(looper.sThreadLocal, looper)

2.Handler创建的时候会通过Looper.myLooper()方法拿到当前Thread对应的Looper,以及其MessageQueue.然后通过sendMessage等方法将消息发送出去。所以对于一个子线程里面如果要使用Handler就必须先通过Looper.prepare()方法创建Looper,否则Handler没有looper可以用。

    public Handler(@Nullable 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 " + Thread.currentThread()
                        + " that has not called Looper.prepare()");
        }
        mQueue = mLooper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }

2.2 消息发送过程分析

2.2.1 Handler部分发送消息的流程

Handler通过sendMessage等方法发送消息时流程为:

sendMessage->sendMessageDelayed->sendMessageAtTime->enqueueMessage

最终通过MessageQueue#enqueueMessage()方法,将msg加入到MessageQueue中。

    public final boolean sendMessage(@NonNull Message msg) {
        return sendMessageDelayed(msg, 0);
    }

   public final boolean sendMessageDelayed(@NonNull Message msg, long delayMillis) {
        if (delayMillis < 0) {
            delayMillis = 0;
        }
        return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
    }

    public boolean sendMessageAtTime(@NonNull 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(@NonNull MessageQueue queue, @NonNull Message msg,
            long uptimeMillis) {
        msg.target = this;
        msg.workSourceUid = ThreadLocalWorkSource.getUid();

        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        return queue.enqueueMessage(msg, uptimeMillis);
    }

2.2.2 MessageQueue消息入队过程分析

Handler发送的Message最终通过MessageQueue#enqueueMessage()加入到MessageQueue中。
下面分析一下消息入队的过程:

    boolean enqueueMessage(Message msg, long when) {
        if (msg.target == null) {//1.先判断当前消息是否有对应的Handler,msg.target就是其对应的Handler
            throw new IllegalArgumentException("Message must have a target.");
        }

        synchronized (this) {//2.加锁,线程安全
            if (msg.isInUse()) {//3.合法性判断
                throw new IllegalStateException(msg + " This message is already in use.");
            }

            if (mQuitting) {//4.合法性判断
                IllegalStateException e = new IllegalStateException(
                        msg.target + " sending message to a Handler on a dead thread");
                Log.w(TAG, e.getMessage(), e);
                msg.recycle();//回收message
                return false;
            }

            msg.markInUse();//5.标记使用,方便做合法性判断
            msg.when = when;//6.待发送消息的时间
            Message p = mMessages;
            boolean needWake;//7.是否执行唤醒操作
            if (p == null || when == 0 || when < p.when) {//8.如果当前没有消息,或者待发送的消息没有延迟,或者待发送的消息时间比当前消息的时间要早,就将当前消息插入到头结点
                // New head, wake up the event queue if blocked.
                msg.next = p;
                mMessages = msg;
                needWake = mBlocked;//IdleHandler执行完毕,mBlocked才为true
            } 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.
                //当IdleHandler执行完毕,并且当前消息是一个异步消息,才会唤醒消息轮训线程
                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);//唤醒消息轮询线程,转到native方法执行。
            }
        }
        return true;
    }

2.3 消息处理过程分析

消息处理从Looper的loop()方法开始,方法太长了,重点关注for循环里面的
queue.next()msg.target.dispatchMessage(msg);,前者是从MessageQueue里取出消息,后者则是调用handler的dispatchMessage()方法

Looper的loop()方法分析:

    public static void loop() {
        final Looper me = myLooper();//1.拿到looper
        if (me == null) {//2.判空处理
            throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
        }

        me.mInLoop = true;
        final MessageQueue queue = me.mQueue;

        boolean slowDeliveryDetected = false;

        for (;;) {//3.for循环遍历
            Message msg = queue.next(); // might block 4.从队列里面拿消息
            if (msg == null) {//5.消息判空处理
                // No message indicates that the message queue is quitting.
                return;
            }
            //...
            try {
                //...
                msg.target.dispatchMessage(msg);//6.消息发送给Handler处理
                //...
            } catch (Exception exception) {
                if (observer != null) {
                    observer.dispatchingThrewException(token, msg, exception);
                }
                throw exception;
            } finally {
			//...
            }

            //...

            msg.recycleUnchecked();
        }
    }

MessageQueue的next()方法分析
next方法本身也是一个for循环,而且是一个死循环。

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

2.4 nativePollOnce流程分析

看不到native层源码,暂不分析

3 Handler常见问题

3.1 Handler造成内存泄漏

这篇文章写的不错,引用这篇文章里的分析结论

Handler导致内存泄漏一般发生在发送延迟消息的时候,当Activity关闭之后,延迟消息还没发出,那么主线程中的MessageQueue就会持有这个消息的引用,而这个消息是持有Handler的引用,而handler作为匿名内部类持有了Activity的引用,所以就有了以下的一条引用链。
主线程 —> threadlocal —> Looper —> MessageQueue —> Message —> Handler —> Activity
其根本原因是因为这条引用链的头头,也就是主线程,是不会被回收的,所以导致Activity无法被回收,出现内存泄漏,其中Handler只能算是导火索。
而我们平时用到的子线程通过Handler更新UI,其原因是因为运行中的子线程不会被回收,而子线程持有了Actiivty的引用(不然也无法调用Activity的Handler),所以就导致内存泄漏了,但是这个情况的主要原因还是在于子线程本身。
所以综合两种情况,在发生内存泄漏的情况中,Handler都不能算是罪魁祸首,罪魁祸首(根本原因)都是他们的头头——线程。

参考文档

探索 Android 消息机制

Handler内存泄露全面分析

标签:Handler,消息,Looper,msg,new,Android,null,机制,looper
来源: https://www.cnblogs.com/cfdroid/p/16321935.html