android消息机制

2020-11-26  本文已影响0人  justin_crashed

在andorid中,系统的行为、用户的输入等事件都会被包装为一个消息,
进行消息发送、处理

关于消息的处理,就离不开Handler、Message、Loop
在平时使用时,Handler多用于多线程之间通信。

Handler多线程通信

先看一下普通使用案例

public class MyActiivty extends Activity {

    private Handler myHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
                if(msg.what=100) {
                    // TODO
                }
            }
        }
    }

    static class MyThread extends Thread() {
        @Overtide
        public void run() {
            super.run();
            Message message = Message.obtain();
            message.what = 100;
            myHandler.sendMessage();
        }
    }

}

上面就是一个简单的在子线程发送消息,回到主线程处理消息的过程,
通过在子线程构造一个message对象,在主线程中获取到该message对象,来处理消息。

所以其实Handler处理多线程通信是通过共享Message对象内存来实现的。
内存是不区分线程的,这种通信原理就是在子线程与主线程共享message内存

所以 那么Handler如何实现多线程通信?
通过 内存共享 实现。

在多线程时,Handler又是如何保证消息如何在正确的线程发送的呢,或者说是如何保证执行的线程是正确的了。
这就要引入我们的Loop、消息队列概念了。

handler处理消息模型:

<img src='../../../images/looper.png' style="zoom:20%" />

handler负责发送、处理消息
looper负责一直轮询消息
messageQueue消息队列,负责存放、取出消息

Looper

讲到looper负责一直轮询消息,但是好像在上面的代码中,都没有使用到looper。

其实是在主线程中,系统已经默认为我们创建了looper,
在ActivityThread.java的main方法中(ActivityThread即为主线程)

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

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

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

我们可以看到,调用了Loop.prepareMainLooper()、Looper.loop()函数,
而且在Looper.loop()后面就抛出异常,
也就是说主线程中loop一旦停止轮询,则会抛出异常闪退。正常情况时,loop就是一直在轮询。

查看Looper的这两个函数

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

在prepareMainLooper中可以看到,不允许调用两次,否则会抛出异常。

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

    // 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 (;;) {
        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);
        }
        // Make sure the observer won't change while processing a transaction.
        final Observer observer = sObserver;

        final long traceTag = me.mTraceTag;
        long slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;
        long slowDeliveryThresholdMs = me.mSlowDeliveryThresholdMs;
        if (thresholdOverride > 0) {
            slowDispatchThresholdMs = thresholdOverride;
            slowDeliveryThresholdMs = thresholdOverride;
        }
        final boolean logSlowDelivery = (slowDeliveryThresholdMs > 0) && (msg.when > 0);
        final boolean logSlowDispatch = (slowDispatchThresholdMs > 0);

        final boolean needStartTime = logSlowDelivery || logSlowDispatch;
        final boolean needEndTime = logSlowDispatch;

        if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
            Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
        }

        final long dispatchStart = needStartTime ? SystemClock.uptimeMillis() : 0;
        final long dispatchEnd;
        Object token = null;
        if (observer != null) {
            token = observer.messageDispatchStarting();
        }
        long origWorkSource = ThreadLocalWorkSource.setUid(msg.workSourceUid);
        try {
            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);
            }
        }
        if (logSlowDelivery) {
            if (slowDeliveryDetected) {
                if ((dispatchStart - msg.when) <= 10) {
                    Slog.w(TAG, "Drained");
                    slowDeliveryDetected = false;
                }
            } else {
                if (showSlowLog(slowDeliveryThresholdMs, msg.when, dispatchStart, "delivery",
                        msg)) {
                    // Once we write a slow delivery log, suppress until the queue drains.
                    slowDeliveryDetected = true;
                }
            }
        }
        if (logSlowDispatch) {
            showSlowLog(slowDispatchThresholdMs, dispatchStart, dispatchEnd, "dispatch", msg);
        }

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

loop函数中,首先获取通过myLooper()函数获取looper对象,如果looper对象为空,则抛出异常,提示必须在当前线程先执行Looper.prepare()
然后获取looper对象持有的messageQueue,
然后就是for(;;)无限循环,获取messageQueue下一条消息
获取到message后调用msg.target.dispatchMessage(msg);
将这条消息发送出去。
最后执行msg.recycleUnchecked(),相当于一个回收利用。

我们看一下myLooper函数

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

说明looper是存放在ThreadLocal中的。
关于ThreadLocal,在之前已经大致讲过了。
ThreadLocal讲解(https://wangchongwei.github.io/blog/2020/08/java-ThreadLocal%E8%A7%A3%E6%9E%90.html
在每一个线程,都存在一个对应且唯一的值

我们可以看一下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));
}

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

可以看到与prepareMainLooper的不同,因为prepareMainLooper是在主线程调用,而主线程很自由一个,
所以直接使用sMainLooper来保存主线程的looper,而且主线程中prepare(false);标示不允许looper退出。

而在子线程时,就是将looper对象保存到sThreadLocal中,sThreadLocal.get()不为null时,会抛出异常。
也就是说子线程中prepare只允许调用一次,保证了每个线程中的looper对象唯一性

然后看到子线程和主线程的另一个差异prepare(false) && prepare(true)
因为andorid,所有事件如:用户的操作、ui的渲染等都是作为消息发送的,而这些都是在主线程操作的,所以在主线程中是不允许退出loop循环,否则抛出异常。

而在子线程中prepare(true),允许退出,其实在子线程中新建handler、looper时,当我们不需要再使用,需要终止loop循环。
此时需要调用:

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

MessageQueue

在上面中已经讲过Looper,looper中持有一个messageQueue
final MessageQueue queue = me.mQueue;
mQueue 在Looper的私有构造函数中被初始化

接下来我们看一下MessageQueue
队列是一种数据结果,FIFO先进先出
MessageQueue 是一个消息队列,默认也是先进先出,有序执行

之前说了,MessageQueue主要用于存放、取出消息。
在Looper中主要用到了messagequeue的next函数,用于取出下一条消息

我们先看一下存放消息

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

如果当前线程已经退出,mQuitting为true,则抛出异常。

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

当全局变量mMessages为空,或者当前传入的when为0, 或者当前when小于全局变量mMessages.when(即时间在前)
其实判断的是两种状态,1:messageQueue队列为空 2:添加的消息执行时间在前
此时将该消息置于队首,
needWake = mBlocked;
如果mBlocked为true,needWake也为true,就是如果之前阻塞则唤醒,反之无需唤醒

再看不满足上面情况下时,即消息队列中已添加过消息,而且要添加的消息.when在上一次添加的消息之后

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

for循环,遍历链表,当找到节点为null即遍历完 || 传入的when小于遍历节点的when(即传入消息的时间在遍历节点时间之前时)
终止循环,将msg.next -> p
原来
prev.next -> n.next -> ... -> n.next -> p -> ...
现在
prev.next -> n.next -> ... -> n.next -> msg.next -> p -> ...

也就是说,message链表是按照when排序的,when越小,在越靠近链头
为何要根据when排序了,其实是因为message执行时间是要按时间排序,要执行时间越小,代表时间越早,所以放在链头

以上是消息队列,入队函数,再看一下出队函数

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


其中有一段代码可以先不看,

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

这一块涉及到消息的同步屏障,放到下面再讲,我们先只看出队时的逻辑
next函数就是取出下一条消息。
开启for循环

if (nextPollTimeoutMillis != 0) {
    Binder.flushPendingCommands();
}

如果nextPollTimeoutMillis不等于0时,会阻塞。

final long now = SystemClock.uptimeMillis();
Message prevMsg = null;
Message msg = mMessages;
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;
}

当当前message不为空时:
如果当前时间小于msg.when,即没到执行时间,则阻塞线程到msg.when时间
将msg.next赋值给全局变量mMessages,再将msg.next指向null
然后返回msg这一个节点,如此不会返回一个链表

如果msg为空,说明队列为空,没有消息,此时赋值nextPollTimeoutMillis = -1;下一次循环时,就会阻塞。

Message

上面讲了消息机制中的Handler、Looper、MessageQueue;
现在我们再讲一下消息的本体Message

首先通过我们在上面的分析,可以知道Message在数据结构上看,是一个链表,而且是只有next指针,所以是个单链表。
Message中没有什么复杂操作,都是一些赋值函数
有两个地址可以注意下

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;
            sPool = this;
            sPoolSize++;
        }
    }
}

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还提供obtain函数,不会直接new 一个Message对象,而是共享之前的对象,改变对象的内部属性。

所以我们在实际使用中都是使用Message.obtain()来构建message对象,而不是一直使用new ,这样可以避免频繁的生成、回收,避免内存抖动。

这种设计被成为 * 享元设计模式 *

Message 同步屏障

上面讲的消息message链表是根据when时间排序,那如果有紧急的消息必须马上处理呢,这个时候不可能等其他先执行而必须是马上执行的事件时,怎么办?

这个时候就可以用到 同步屏障
我们可以看一下上面讲到的代码

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

原理就是将一个消息状态标示符isAsynchronous设置为false,此时发送消息时,handler不会绑定到msg上,msg.target就为null,
在for循环中首先对msg.target做检测,当msg对象不为空,而msg.target为空时,此时就是message链表中有同步屏障,
此时不会依次按链表来取出消息,而是通过遍历取出message链表中的同步消息进行处理。
当所有的同步消息都执行完毕,就会remove同步屏障,又会回到之前的按序取消息的方式。

设置与去除同步屏障的方法在MessageQueue类中

// 设置同步屏障
postSyncBarrier()
// 去除同步屏障
removeSyncBarrier()

但这个两个方法都是使用了hide注解,我们是无法直接调用的,只能系统内部使用。

总结

handler消息机制大概流程:
生成Looper对象,生成Handler对象,Lopper.looper循环
在Handler构造函数内,获取到上面生成的looper对象,通过ThreadLocal保存到对应的线程,与MessageQueue绑定
在需要发送消息的地方调用handler.sendMessage(),在sendMessage时,将message与handler绑定,将message.target赋值为当前handler
同时,sendMessage时,调用messageQueue.enqueueMessage将message放入消息队列。
同时,Looper.loop()在循环一直取出消息message,然后通过message.target获取到handler对象,最终回调到handler.handlerMessage函数。

这样消息从产生到处理流程就走完了。

总结提问:

答:loop()循环与ANR是两个不相关的事情,loop只是循环事件,ANR是处理事件耗时,导致无法响应用户的下一次输入。
系统的ANR弹窗都是通过消息机制发送,并弹出提示窗的。

上一篇下一篇

猜你喜欢

热点阅读