💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
很久没写博客了,一直想写下android关于源码分析的文章,今天就来分析下android中的异步消息处理机制Handler的原理。Handler的用法我们都再熟悉不过了。其最经典的用法如下: ~~~ Looper.prepare(); ~~~ ~~~ private Handler handlerWenzhang = new Handler(){ public void handleMessage(Message msg) { switch (msg.what) { case 0:break; case 1:break; default:break; } }; }; ~~~ ~~~ Looper.loop(); ~~~ 接下来在子线程中发送消息。 ~~~ Message message = new Message(); Bundle bundle = new Bundle(); bundle.putString("message", "1"); message.setData(bundle); handler.sendMessage(message); ~~~ 以上handleMessage()方法中就是在主线程调用,一般用于进行UI操作,而sendMessage()方法是在子线程中调用,把结果传到主线程,这就实现了异步通信。使用方法用简单,但是只会用而不知道其原理往往会很不爽,所以让我们来看看handler的源码实现吧。 我们来细究handler的内部原理。在介绍handler之前我们要先了解下什么是Looper,Handler和MessageQueue。 Handler:用于在子线程发送消息,在主线程获得和处理消息; MessageQueue:是一个管理消息的队列,消息是先入先出的。 Looper:负责读取MessageQueue中的消息,读取到后交给Handler处理。要注意的是每个线程都必须定义一个Looper,之所以平时我们在使用时很少定义Looper是因为android的主线程中已经默认给我们定义好了,所以不需要再次定义。 程序一开始就应该调用Looper.prepare()来定义Looper,首先看看Looper的代码: ~~~ 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并放入sThreadLocal中,这样保证线程中只有一个Looper。既然创建了Looper,就先看看它的构造方法: ~~~ private Looper(boolean quitAllowed) { mQueue = new MessageQueue(quitAllowed); mThread = Thread.currentThread(); } ~~~ 很简单,创建了一个消息队列。接着我们来看看定义了Handler,前面我们已经提过,Handler一般在子线程中发送消息,在主线程中从MessageQueue中取数据,那么具体怎么实现的呢,先看看Handler的构造方法: ~~~ 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; } ~~~ 主要看看第10行代码,通过Looper的myLooper获取到线程中的Looper对象,代码如下: ~~~ public static Looper myLooper() { return sThreadLocal.get(); } ~~~ 然后第15行代码就是获得Looper的MessageQuene对象,这样Handler就和MessageQuene连接起来了。接着我们调用Looper.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 Printer logging = me.mLogging; if (logging != null) { logging.println(">>>>> Dispatching to " + msg.target + " " + msg.callback + ": " + msg.what); } msg.target.dispatchMessage(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.recycle(); } } ~~~ 以上代码很长,首先是先获取Looper对象,如果不存在抛异常。queue.next()就是消息出队列的意思,如果有消息就将其出队列,其中for循环其到一个不断取数据的作用,如果没数据,就阻塞。调用msg.target.dispatchMessage(msg)对获得的消息进行处理,通过前文我们可以猜测target应该是Handler。那么就先把它当Handler,接下来当然就是看Handler的dispatchMessage()方法啦。 ~~~ public void dispatchMessage(Message msg) { if (msg.callback != null) { handleCallback(msg); } else { if (mCallback != null) { if (mCallback.handleMessage(msg)) { return; } } handleMessage(msg); } } ~~~ 看看handleMessage()方法,有没有很熟悉。而在Handler中handleMessage()是一个空方法。 ~~~ public void handleMessage(Message msg) { } ~~~ 所以我们如果要对消息进行处理就只要重写handleMessage()方法即可。到此是不是对Handler如何取数据和如何处理数据相当清楚啦。但我们还有些疑问,Handler是如何发送消息的,消息如何进入队列的。还有就是为什么上面的target是Handler。要弄明白这些,就只能继续看代码。 我们来看看发送的代码,一般调用sendMessage()、sendEmptyMessage()等方法来发送消息。追踪源码可知无论是sendMessage()还是sendEmptyMessage最终都调用的是sendMessageAtTime(Message msg, long uptimeMillis)方法。让我们来看看它的源码: ~~~ 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); } ~~~ 方法很简单,传入两个参数,msg是我们发送的消息,uptimMills指发送消息的时间。若像延时发送可设置此值。最后返回enqueueMessage方法。让我们继续看看enqueueMessage实现了什么功能。 ~~~ private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) { msg.target = this; if (mAsynchronous) { msg.setAsynchronous(true); } return queue.enqueueMessage(msg, uptimeMillis); } ~~~ 看到第二行,我们是不是明白了什么。在这里把msg.target赋值Handler,这就回答了上面的问题。最后调用的是MessageQueue中的enqueueMessage方法。查看下enqueueMessage的方法: ~~~ boolean enqueueMessage(Message msg, long when) { if (msg.isInUse()) { throw new AndroidRuntimeException(msg + " This message is already in use."); } if (msg.target == null) { throw new AndroidRuntimeException("Message must have a target."); } synchronized (this) { if (mQuitting) { RuntimeException e = new RuntimeException( msg.target + " sending message to a Handler on a dead thread"); Log.w("MessageQueue", e.getMessage(), e); return false; } 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; } ~~~ 这个就是入队的意思。将消息传入MessageQueue中。看上面代码才知道,原来MessageQueue并不是一个集合把消息都存起来。它是按传入的时间参数来对消息进行排序。这就完成了消息的入队。到此我们整个Handler的处理过程就讲完了,接下来总结一下: Handler在子线程中通过sendMessage()方法经enqueueMessage将消息传入到MessageQueue队列中。此时仍在子线程中。Handler再通过loop()方法获得消息并在handleMessage方法中处理。Handler是建立在主线程中的,所以handlerMessage就是在主线程处理相关操作。 关于HandleMessage的讲解就到这里,可能个人的分析有出错的地方,希望指出。