Android-消息机制

Android-Handler
Android-Looper
Android-MessageQueue
Android-Message

一、消息机制概述

1.消息机制的简介

在Android中使用消息机制,我们首先想到的就是Handler。没错,Handler是 Android消息机制的上层接口。Handler的使用过程很简单,通过它可以轻松地将一 个任务切换到Handler所在的线程中去执行。通常情况下,Handler的使用场景就是 更新UI。
如下就是使用消息机制的一个简单实例:

public class MainActivity extends AppCompatActivity {
    
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            System.out.println(msg.what);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);

        new Thread(new Runnable() {
            @Override
            public void run() {
                //...............耗时操作
                Message message = Message.obtain();
                message.what = 1;
                mHandler.sendMessage(message);
            }
        }).start();
    }
}

在子线程中,进行耗时操作,执行完操作后,发送消息,通知主线程更新UI。这便 是消息机制的典型应用场景。我们通常只会接触到Handler和Message来完成消息 机制,其实内部还有两大助手来共同完成消息传递。

2.消息机制的模型

消息机制主要包含:MessageQueue,Handler和Looper这三大部分,以及
Message,下面我们一一介绍。

  • Message:需要传递的消息,可以传递数据;
  • MessageQueue:消息队列,但是它的内部实现并不是用的队列,实际上是通过一 个单链表的数据结构来维护消息列表,因为单链表在插入和删除上比较有优势。主 要功能向消息池投递消息(MessageQueue.enqueueMessage)和取走消息池的消息 (MessageQueue.next);
  • Handler:消息辅助类,主要功能向消息池发送各种消息事件 (Handler.sendMessage)和处理相应消息事件(Handler.handleMessage);
  • Looper:不断循环执行(Looper.loop),从MessageQueue中读取消息,按分发机制 将消息分发给目标处理者。

3.消息机制的架构

  • 消息机制的运行流程:在子线程执行完耗时操作,当Handler发送消息时,将会调用MessageQueue.enqueueMessage,向消息队列中添加消息。
  • 当通过Looper.loop开启循环后,会不断地从线程池中读取消息,即调
    用MessageQueue.next。
  • 然后调用目标Handler(即发送该消息的Handler)
    的dispatchMessage方法传递消息,然后返回到Handler所在线程,目标Handler收到消息,调用 handleMessage方法,接收消息,处理消息。

每个线程中只能存在一个 Looper,Looper是保存在ThreadLocal中的。主线程(UI线程)已经创建了一个 Looper,所以在主线程中不需要再创建Looper,但是在其他线程中需要创建 Looper。
每个线程中可以有多个Handler,即一个Looper可以处理来自多个Handler 的消息。
Looper中维护一个MessageQueue,来维护消息队列,消息队列中的 Message可以来自不同的Handler。

下面是消息机制的整体架构图,接下来我们将慢慢解剖整个架构。


从中我们可以看出:

  • Looper有一个MessageQueue消息队列;
  • MessageQueue有一组待处理的Message;
  • Message中记录发送和处理消息的Handler;
  • Handler中有Looper和MessageQueue。

二、消息机制的源码解析

1.Looper

要想使用消息机制,首先要创建一个Looper。
初始化Looper
无参情况下,默认调用 prepare(true); 表示的是这个Looper可以退出,而对于 false的情况则表示当前Looper不可以退出。

    /**
     * Initialize the current thread as a looper.
     * This gives you a chance to create handlers that then reference
     * this looper, before actually starting the loop. Be sure to call
     * {@link #loop()} after calling this method, and end it by calling
     * {@link #quit()}.
     */
    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));
    }

这里看出,不能重复创建Looper,只能创建一个。创建Looper,并保存在 ThreadLocal。其中ThreadLocal是线程本地存储区(Thread Local Storage,简称 为TLS),每个线程都有自己的私有的本地存储区域,不同线程之间彼此不能访问 对方的TLS区域。

开启Looper

    /**
     * TODO 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(); //获取TLS存储的Looper对象
        if (me == null) {
            throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
        }

        // 消息队列
        final MessageQueue queue = me.mQueue; //获取Looper对象中的消息 队列

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

        // 进入loop的主循环方法
        for (; ; ) {
            Message msg = queue.next(); // might block 可能会阻塞,因为next()方法可能会无限循环

            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
            // 默认为null,可通过setMessageLogging()方法来指定输出,用于debug功能
            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的目标Handler, 然后用于分发Message 这个target 就是发送消息的那个 Handler
                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()进入循环模式,不断重复下面的操作,直到消息为空时退出循环: 读取MessageQueue的下一条Message(关于next(),后面详细介绍); 把Message分发给相应的target。
当next()取出下一条消息时,队列中已经没有消息时,next()会无限循环,产生阻 塞。等待MessageQueue中加入消息,然后重新唤醒。
主线程中不需要自己创建Looper,这是由于在程序启动的时候,系统已经帮我们自 动调用了 Looper.prepare() 方法。查看ActivityThread中的 main() 方法,代 码如下所示:

ActivityThread main函数

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("");
        
        // TODO 开启 
        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);

        //  TODO 启动循环 
        Looper.loop();

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

其中 `prepareMainLooper() 方法会调用 prepare(false) 方法。

2.创建Handler

    public Handler() {
        this(null, false);
    }
   
    public Handler(boolean async) {
        this(null, async);
    }

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

    public Handler(@Nullable Callback callback, boolean async) {
        if (FIND_POTENTIAL_LEAKS) {
            final Class 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());
            }
        }

        //拿当前线程的Looper构建消息循环系统
        //如果当前线程没有 初始化 looper 就会报错
        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;   // 异步
    }

对于Handler的无参构造方法,默认采用当前线程TLS中的Looper对象,并且 callback回调方法为null,且消息为同步处理方式。只要执行的 Looper.prepare() 方法,那么便可以获取有效的Looper对象。

3.发送消息

发送消息有几种方式,但是归根结底都是调用了 sendMessageAtTime() 方法。
在子线程中通过Handler的post()方式或send()方式发送消息,最终都是调用
了 sendMessageAtTime() 方法。

post方法

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

public final boolean postAtTime(Runnable r, long uptimeMillis){
    return sendMessageAtTime(getPostMessage(r), uptimeMillis);
}

public final boolean postAtTime(Runnable r, Object token, long uptimeMillis) {
    return sendMessageAtTime(getPostMessage(r, token), uptimeMillis);
}

 public final boolean postDelayed(Runnable r, long delayMillis) {
    return sendMessageDelayed(getPostMessage(r), delayMillis);
}

send方法

public final boolean sendMessage(Message msg) {
    return sendMessageDelayed(msg, 0);
}
 
public final boolean sendEmptyMessage(int what){
    return sendEmptyMessageDelayed(what, 0);
}

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

public final boolean sendEmptyMessageAtTime(int what, long uptimeMillis) {
    Message msg = Message.obtain();
    msg.what = what;
    return sendMessageAtTime(msg, uptimeMillis);
}

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

就连子线程中调用Activity中的runOnUiThread()中更新UI,其实也是发送消息通知 主线程更新UI,最终也会调用 sendMessageAtTime() 方法。

public final void runOnUiThread(Runnable action) {
    if (Thread.currentThread() != mUiThread) {
        mHandler.post(action); 
    } else {
        action.run(); 
    }
}

如果当前的线程不等于UI线程(主线程),就去调用Handler的post()方法,最终会调 用 sendMessageAtTime() 方法。否则就直接调用Runnable对象的run()方法。

下面我们就来一探究竟,到底 sendMessageAtTime() 方法有什么作用? sendMessageAtTime()

public boolean sendMessageAtTime(@NonNull Message msg, long uptimeMillis) {
        //其中mQueue是消息队列,从Looper中获取的
        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) {
        // Handler 保存进来了 looper的时候使用这个Handler 处理消息的
        // 为什么使用匿名内部类来创建Handler的方法会有内存泄漏的风险?
        msg.target = this;
        // 线程数据
        msg.workSourceUid = ThreadLocalWorkSource.getUid();
        // 异步
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        // 调用的是 Looper 的 Queen 的函数
        return queue.enqueueMessage(msg, uptimeMillis);
    }

MessageQueue#enqueueMessage()


boolean enqueueMessage(Message msg, long when) {
       // 每一个Message必须有一个target 这个target就是发送/处理消息的Handler
       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) { //正在退出时,回收msg,加入到消息池
               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;
           //p为null(代表MessageQueue没有消息) 或者msg的触发时间是队列中最早的, 则进入该该分支
           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是按照Message触发时间的先后顺序排列的,队头的消息是将要最 早触发的消息。当有消息需要加入消息队列时,会从队列头开始遍历,直到找到消 息应该插入的合适位置,以保证所有消息的时间顺序。

4.获取消息

当发送了消息后,在MessageQueue维护了消息队列,然后在Looper中通
过 loop() 方法,不断地获取消息。上面对 loop() 方法进行了介绍,其中最重 要的是调用了 queue.next() 方法,通过该方法来提取下一条信息。下面我们来看一下 next() 方法的具体流程。

MessageQueue#next()

 @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 // 循环迭代的首次为-1
        int nextPollTimeoutMillis = 0;
        for (;;) {
            if (nextPollTimeoutMillis != 0) {
                Binder.flushPendingCommands();
            }

            //阻塞操作,当等待nextPollTimeoutMillis时长,或者消息队列被唤醒 ,都会返回
            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.
                    //当消息Handler为空时,查询MessageQueue中的下一条异步 消息msg,为空则退出循环。
                    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;
                        }
                        //设置消息的使用状态,即flags |= FLAG_IN_USE
                        msg.next = null;
                        if (DEBUG) Log.v(TAG, "Returning message: " + msg);
                        msg.markInUse();
                        //成功地获取MessageQueue中的下一 条即将要执行的消息
                        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;
        }
    }

nativePollOnce是阻塞操作,其中nextPollTimeoutMillis代表下一个消息到来前,还 需要等待的时长;当nextPollTimeoutMillis = -1时,表示消息队列中无消息,会一直 等待下去。
可以看出 next() 方法根据消息的触发时间,获取下一条需要执行的消息,队列中 消息为空时,则会进行阻塞操作。

5.分发消息

在loop()方法中,获取到下一条消息后,执行msg.target.dispatchMessage(msg)
,来分发消息到目标Handler对象。 方法的执行流程。
下面就来具体看下dispatchMessage(msg)方法的执行流程。

dispatchMessage()

    /**
     * Handle system messages here.
     */
    public void dispatchMessage(@NonNull Message msg) {
        
        //当Message存在回调方法,回调msg.callback.run()方法;
        if (msg.callback != null) {
            handleCallback(msg);
        } else {
            if (mCallback != null) {
                //当Handler存在Callback成员变量时,回调方法handleMessage();
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            //Handler自身的回调方法handleMessage()
            handleMessage(msg);
        }
    }

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

    /**
     * Subclasses must implement this to receive messages.
     * 子类必须实现它来接收消息。
     */
    public void handleMessage(@NonNull Message msg) {
    }

分发消息流程:
  • 当Message的msg.callback不为空时,则回调方法 msg.callback.run() ;
  • 当Handler的mCallback不为空时,则回调方法mCallback.handleMessage(msg);
  • 最后调用Handler自身的回调方法handleMessage(msg),该方法默认为空Handler子类通过覆写该方法来完成具体的逻辑。
消息分发的优先级:
  • Message的回调方法:message.callback.run();优先级最高。
  • Handler中Callback的回调方法:mCallback.handleMessage(msg),优先级仅次于1。
  • Handler的默认方法: Handler.handleMessage(msg) ,优先级最低。

三、总结

你可能感兴趣的:(Android-消息机制)