Android的消息机制
2016-01-06 16:17
435 查看
转载请注明出处:/article/7707981.html
2015已成为过去,转眼间迎来了2016。自己已经从事Android开发两年了,看的各种书籍和资料也不少,可是自己从来也都没有把自己学到的东西整理出来分享给大家,今天在新的一年,自己把以前学到的一些知识点总结梳理分享出来,以此共勉。
前面都是废话,现在我们进入主题,今天我要给大家分享的是Android的消息机制。相信大家对Android的消息的使用并不陌生,当我们在UI线程(主线程)中另起线程来完成耗时操作或者访问网络的时候,等线程结束如果有UI需要更新,这时就会使用Handler来发送消息到主线程去更新UI。原因大家想必都清楚,因为Android的UI控件不是线程安全的,所以在线程中去访问UI控件是不允许的。
其实上面只是Handler的常用情景,其实Handler还有别的情景,那么下面我们就开始讲解Handler消息机制吧。
我们知道Handler创建的时候会采用当前线程的Looper来构造消息循环系统,那么Handler的内部是如何获取到当前线程的Looper的呢?
这就要是用ThreadLocal了,下面首先介绍ThreadLocal。
在上面代码中,在主线程中设置mBooleanThreadLocal的值为true,在子线程1中设置为false,在子线程2中不设置。打印输出结果如下:
相信大家对存储Looper的ThreadLocal有一个大概的了解了,下面我们一次介绍MessageQueue,Handler,Looper的工作机制原理。
MessageQueue就是Android中的消息队列,它主要包含了两个操作,插入和读取。读取操作本身会伴随这删除操作,插入和读取对应的方法分别为enqueueMessage和next。其中enqueueMessage的作用是往消息队列中插入一条消息,而next的作用是从消息队列中取出一条消息并从中移除,下面主要看一下这两个方法的实现。
enqueueMessage的源码如下所示:
从它的实现来看,它的主要操作就是单链表的插入操作。这里就不多说了,下面来看next方法的实现:
可以发现next方法是一个无限循环的方法,如果消息队列中没有消息,那么next方法会一直阻塞在这里。有新消息来时,next方法会返回这条消息并将其从单链表中移除。
它会创建一个MessageQueue,然后将当前线程的对象保存起来。
我们知道Handler的工作需要Looper,没有Looper的线程就会报错,那么如何为一个线程创建Looper呢?如下:
Looper除了prepare方法,还提供了prepareMainLooper方法,这个方法主要是给主线程ActivityThread创建Looper使用的,其本质也是通过prepare来实现的。同时Looper提供了一个getMainLooper方法通过他可以在任何地方获取到主线程的Looper。
Looper最重要的方法就是loop方法了。只有调用loop方法后,消息系统才会真正起作用。loop的源码如下:
从上面源码可以看出loop方法是个死循环,唯一跳出循环的的方式是MessageQueue的next方法返回了null值。Looper在获取到新的消息后的处理代码从上面可以看出是:msg.target.dispatchMessage(msg),这里的msg.target是发送消息的Handler对象,这样Handler发送的消息最终还是交给它自己的dispatchMessage()方法来处理了。而且这个方法是在Looper中执行的,这样就成功的把逻辑切换到指定的线程中去了。
注意:Looper也是可以退出的,提供了quit和quitSafely两个给方法,二者的区别是,quit直接退出Looper,而quitSafely只是设定了一个退出标记,当消息队列的消息处理完毕后才会安全的退出,有兴趣的朋友可以去查看源码。这里我就不贴源码了。因为Looper是个死循环,建议在不需要的时候要终止Looper。
从上面的源码可以看出,Handler发送消息的过程仅仅是向消息队列中插入了一条消息,MessageQueue的next方法会返回这条消息给Looper,Looper收到消息后就开始处理了,最终消息由Looper交给了Handler处理,即Handler的dispatMessage方法会被调用,这时Handler就进入了处理消息的阶段。despatchMessage方法实现如下:
从源码我们可以分析出:首先,会检查Message的callback是否为null,不为null就通过handleCallback来处理消息了,这个Message的callback是一个Runnable对象,实际上就是Handler的post方法所传递的Runnable参数。
其次,检查mCallback是否为null,不为null就调用mCallback的handleMessage方法来处理消息,这个mCallback是个什么东西呢?实际上,大家在创建Handler的时候有时候是这样创建的:Handler handler = new Handler(callback);这里的“callback”就是我们上面提到的mCallback了。这样就不用派生出一个Handler的子类并重写其handleMessage方法来处理消息了。
如果mCallback为null或者mCallback处理消息后返回false,那么消息会进一步让Handler子类的handleMessage方法来处理。
总结上面的消息处理流程,我画了个流程图方便大家理解,如下:
写了一个下午,总算完成Android消息机制的解析。由于自己是第一次自己动手写博客,如果有什么纰漏,不对的地方,也请各位大神指出,谢谢。
2015已成为过去,转眼间迎来了2016。自己已经从事Android开发两年了,看的各种书籍和资料也不少,可是自己从来也都没有把自己学到的东西整理出来分享给大家,今天在新的一年,自己把以前学到的一些知识点总结梳理分享出来,以此共勉。
前面都是废话,现在我们进入主题,今天我要给大家分享的是Android的消息机制。相信大家对Android的消息的使用并不陌生,当我们在UI线程(主线程)中另起线程来完成耗时操作或者访问网络的时候,等线程结束如果有UI需要更新,这时就会使用Handler来发送消息到主线程去更新UI。原因大家想必都清楚,因为Android的UI控件不是线程安全的,所以在线程中去访问UI控件是不允许的。
其实上面只是Handler的常用情景,其实Handler还有别的情景,那么下面我们就开始讲解Handler消息机制吧。
一,Android的消息机制概述
Android的消息机制主要是指Handler的工作机制以及所附带的MessageQueue和Looper的工作过程。这三者实际上是一个整体,只是我们平时开发的过程中比较多接触Handler而已。Handler的运行需要底层的MessageQueue和Looper做支撑。MessageQueue的中文翻译的意思是“消息队列”,然而它内部并不是队列结构,而是采用单链表的数据结构来存储消息列表。MessageQueue只是把消息存储起来,Looper的作用是消息循环,Looper会无限循环的方式去查找是否有新消息,有的话就处理,否则就一直等待着。我们知道Handler创建的时候会采用当前线程的Looper来构造消息循环系统,那么Handler的内部是如何获取到当前线程的Looper的呢?
这就要是用ThreadLocal了,下面首先介绍ThreadLocal。
二,ThreadLocal的工作原理
ThreadLocal是一个线程内部的数据存储类,通过它可以在指定的线程中存储数据,数据存储以后,只有在指定的线程中可以获取到存储的数据,对于其他线程来说则无法获取到数据。下面通过一个实际的例子来演示ThreadLocal的真正含义。首先定义一个ThreadLocal对象,如下:private ThreadLocal<Boolean> mBooleanThreadLocal = new ThreadLocal<Boolean>();然后分别在主线程、子线程1和子线程2中设置和访问它的值,代码如下:
mBooleanThreadLocal.set(true); Log.d(TAG, "[Thead#main]mBooleanTheadLocal=" + mBooleanThreadLocal.get()); new Thread("Thread#1") { @override public void run() { mBooleanThreadLocal.set(false); Log.d(TAG, "[Thead#1]mBooleanTheadLocal=" + mBooleanThreadLocal.get()); }; }.start(); new Thread("Thread#2") { @override public void run() { Log.d(TAG, "[Thead#2]mBooleanTheadLocal=" + mBooleanThreadLocal.get()); }; }.start();
在上面代码中,在主线程中设置mBooleanThreadLocal的值为true,在子线程1中设置为false,在子线程2中不设置。打印输出结果如下:
D/TActivity(8676) : [Thread#main]mBooleanThreadLocal=true D/TActivity(8676) : [Thread#1]mBooleanThreadLocal=false D/TActivity(8676) : [Thread#2]mBooleanThreadLocal=null从上面可以清楚的看到ThreadLocal可以在不同的线程中维护一套数据副本并且彼此互补干扰。大家可以去查看ThreadLocal的源码可以发现,在不同的线程中访问同一个ThreadLocal的set和get方法所做的读写操作仅限于各自的线程内部,这就是为什么ThreadLocal可以在多个线程中互不干扰的存储和修改数据。理解ThreadLocal的实现方式有助于理解Looper的工作原理。
相信大家对存储Looper的ThreadLocal有一个大概的了解了,下面我们一次介绍MessageQueue,Handler,Looper的工作机制原理。
三,MessageQueue的工作原理
相信大家对存储Looper的ThreadLocal有一个大概的了解了,下面我们一次介绍MessageQueue,Handler,Looper的工作机制原理。MessageQueue就是Android中的消息队列,它主要包含了两个操作,插入和读取。读取操作本身会伴随这删除操作,插入和读取对应的方法分别为enqueueMessage和next。其中enqueueMessage的作用是往消息队列中插入一条消息,而next的作用是从消息队列中取出一条消息并从中移除,下面主要看一下这两个方法的实现。
enqueueMessage的源码如下所示:
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("MessageQueue", 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; }
从它的实现来看,它的主要操作就是单链表的插入操作。这里就不多说了,下面来看next方法的实现:
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 (false) Log.v("MessageQueue", "Returning message: " + msg); 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("MessageQueue", "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; } }
可以发现next方法是一个无限循环的方法,如果消息队列中没有消息,那么next方法会一直阻塞在这里。有新消息来时,next方法会返回这条消息并将其从单链表中移除。
四,Looper的工作原理
Looper在Android的消息机制中扮演中消息循环的角色,具体地就是它会不停的从MessageQueue中查看是否有新消息,如果有机会立刻处理,否则就一直阻塞在那里。首先我们来看一下Looper源码的构造方法如下:private Looper(boolean quitAllowed) { mQueue = new MessageQueue(quitAllowed); mThread = Thread.currentThread(); }
它会创建一个MessageQueue,然后将当前线程的对象保存起来。
我们知道Handler的工作需要Looper,没有Looper的线程就会报错,那么如何为一个线程创建Looper呢?如下:
new Thread("Thread#2") { public void run() { Looper.prepare(); Handler handler = new Handler(); Looper.loop(); }; }.start();
Looper除了prepare方法,还提供了prepareMainLooper方法,这个方法主要是给主线程ActivityThread创建Looper使用的,其本质也是通过prepare来实现的。同时Looper提供了一个getMainLooper方法通过他可以在任何地方获取到主线程的Looper。
Looper最重要的方法就是loop方法了。只有调用loop方法后,消息系统才会真正起作用。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 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.recycleUnchecked(); } }
从上面源码可以看出loop方法是个死循环,唯一跳出循环的的方式是MessageQueue的next方法返回了null值。Looper在获取到新的消息后的处理代码从上面可以看出是:msg.target.dispatchMessage(msg),这里的msg.target是发送消息的Handler对象,这样Handler发送的消息最终还是交给它自己的dispatchMessage()方法来处理了。而且这个方法是在Looper中执行的,这样就成功的把逻辑切换到指定的线程中去了。
注意:Looper也是可以退出的,提供了quit和quitSafely两个给方法,二者的区别是,quit直接退出Looper,而quitSafely只是设定了一个退出标记,当消息队列的消息处理完毕后才会安全的退出,有兴趣的朋友可以去查看源码。这里我就不贴源码了。因为Looper是个死循环,建议在不需要的时候要终止Looper。
五,Handler的工作原理
我们上面已经讲过了,Handler的主要工作是消息的发送和接受,当然消息的处理实际上也是Handler来完成。消息的发送是通过post的一些列方法和send的一系列方法来实现,post的一些列方法最终是通过send来实现的,这里大家可以去查看源码,我就不贴出源码了。下面我们来看一下sendMessage方法的源码如下:public final boolean sendMessage(Message msg) { return sendMessageDelayed(msg, 0); }
public final boolean sendMessageDelayed(Message msg, long delayMillis) { if (delayMillis < 0) { delayMillis = 0; } return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis); }
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); }
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) { msg.target = this; if (mAsynchronous) { msg.setAsynchronous(true); } return queue.enqueueMessage(msg, uptimeMillis); }
从上面的源码可以看出,Handler发送消息的过程仅仅是向消息队列中插入了一条消息,MessageQueue的next方法会返回这条消息给Looper,Looper收到消息后就开始处理了,最终消息由Looper交给了Handler处理,即Handler的dispatMessage方法会被调用,这时Handler就进入了处理消息的阶段。despatchMessage方法实现如下:
public void dispatchMessage(Message msg) { if (msg.callback != null) { handleCallback(msg); } else { if (mCallback != null) { if (mCallback.handleMessage(msg)) { return; } } handleMessage(msg); } }
从源码我们可以分析出:首先,会检查Message的callback是否为null,不为null就通过handleCallback来处理消息了,这个Message的callback是一个Runnable对象,实际上就是Handler的post方法所传递的Runnable参数。
其次,检查mCallback是否为null,不为null就调用mCallback的handleMessage方法来处理消息,这个mCallback是个什么东西呢?实际上,大家在创建Handler的时候有时候是这样创建的:Handler handler = new Handler(callback);这里的“callback”就是我们上面提到的mCallback了。这样就不用派生出一个Handler的子类并重写其handleMessage方法来处理消息了。
如果mCallback为null或者mCallback处理消息后返回false,那么消息会进一步让Handler子类的handleMessage方法来处理。
总结上面的消息处理流程,我画了个流程图方便大家理解,如下:
写了一个下午,总算完成Android消息机制的解析。由于自己是第一次自己动手写博客,如果有什么纰漏,不对的地方,也请各位大神指出,谢谢。
相关文章推荐
- Android Studio使用教程(二)
- android 之popupWindow 在指定位置上的显示
- Android卸载反馈
- Android Studio使用教程(一)
- Android 内存分析工具MAT(中)
- android looper和handler
- android开发第三方聊天导入
- android开发游记:xml配置图形文件
- Android编程实现自定义系统菜单背景的方法
- Android相关的技术博客及文章收集
- WindowManager: android.view.WindowLeaked: Activity has leaked window com.android.internal.policy.imp
- Android学习笔记--广播(Broadcast)
- Android Theme详细
- Android--支付宝 android sdk 使用方法
- 【Android开源框架】使用andbase开发框架实现绘制折线图
- Android所有activity如何公用一个view对象
- 一些关于android大神开源项目
- Android开发之ADT导入Support Library
- android 实现应用内语言切换
- 翻书动画实现