不忘初心 砥砺前行, Tomorrow Is Another Day !
本文概要:
- 对于Handler两个常见的问题
- messageQueue、Looper、Handler之间的关系
前言:
Android的消息机制主要是指Handler运行机制,handler它的作用就是切换到指定线程执行任务,记住是切换到指定线程执行任务,可以子线程也可以是主线程,只是在实际开发中经常应用于更新UI.在handler底层需要MessageQueue与Looper支持.接着我们来具体介绍.
一. 两个常见问题:
- android为什么不允许在子线程更新UI?
为了避免多线程,更新UI线程是不安全的.复制代码
- 线程不安全,对UI访问为什么不采用锁的机制?
锁机制会造成逻辑复杂并且降低访问UI的效率,阻塞某些线程的执行.复制代码
二. messageQueue、Looper、Handler之间的关系
- messageQueue:存储消息
- looper: 处理消息,存储在ThreadLocal中.
- Handler: 是基于looper构建内部消息循环系统.
对于ThreadLocal如果暂不了解,可以先阅读,这样更容易理解Handler消息机制.
接下来我们看三剑客的各自工作原理,首先看messageQueue.
messageQueue
messageQueue称为消息队列,用来存储消息.它涉及到两个关键操作一个就是将消息插入消息队列,另一个就是读取消息并且移除该消息.
涉及的两个操作的方法
- enqueueMessage: 插入消息
- next: 读取消息接着移除消息
这里重点说下next方法,它是一个无线循环的方法,会不断的从消息队列中读取消息并且移除,如果此时无消息,那么将会一直处于阻塞中.
对于messageQueue暂时了解到这里,接着看Looper,下面还会涉及到消息队列.
Looper
Looper称为消息循环,在消息机制中扮演着很重要的角色. 不断的从消息队列中获取新消息.有消息就处理,无消息也一直处于阻塞中.
1. 首先看Looper的构造方法.
对应源码
private Looper(boolean quitAllowed) { //初始化一个消息队列 mQueue = new MessageQueue(quitAllowed); //获取当前线程 mThread = Thread.currentThread();}复制代码
上面looper的构造方法是一个private修饰,所以一般情况不能直接调用,系统提供了prepare()方法来创建Looper.
对应源码
public static void prepare() { prepare(true);}private static void prepare(boolean quitAllowed) { if (sThreadLocal.get() != null) { //说明一个线程只能绑定一个looper throw new RuntimeException("Only one Looper may be created per thread"); } //将Looper保存于ThreadLocal中. sThreadLocal.set(new Looper(quitAllowed));}复制代码
对于主线程的特殊性,系统还提供了prepareMainLooper( )来初始化Looper,其主要供ActivityThread使用.并且系统还提供了getMainLooper( )方法,这样就可以在任何地方获取主线程的looper.
2. 接着看Looper的loop方法.
对应源码
public static void loop() { final Looper me = myLooper(); if (me == null) { //1.获取当前线程的looper,没有直接报错. 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 (;;) { /* * 2.调用MessageQueue的next获取消息. * (非常重要) */ 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); } final long slowDispatchThresholdMs = me.mSlowDispatchThresholdMs; final long traceTag = me.mTraceTag; if (traceTag != 0 && Trace.isTagEnabled(traceTag)) { Trace.traceBegin(traceTag, msg.target.getTraceName(msg)); } final long start = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis(); final long end; try { //3. (非常重要)调用handler分发处理消息 msg.target.dispatchMessage(msg); end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis(); } finally { if (traceTag != 0) { Trace.traceEnd(traceTag); } } //...省略部分代码 } }复制代码
loop方法代表开启消息循环,具体流程可以看注释这样更清晰.这里特别提一点,需要注意的loop是一个无限循环,不断的从messageQueue中获取消息,在之前我们已经了解到next获取消息时,如果没有则一直处于阻塞状态,所以这里同样也是处于阻塞状态.只有当msg为null的时候才会退出,所以在自定义looper时需要在适当的时候,调用quit/quitSafely退出looper.也间接的退出了messageQueue.可以看下面源码.
对应源码
public void quit() { //调用了MessageQueue mQueue.quit(false);}public void quitSafely() { mQueue.quit(true);}复制代码
另外在分发消息时,回调了Handler的dispatchMessage,此方法是在创建handler所使用的Looper中去执行的,而looper又与当前线程相绑定的.也就顺利的切换到指定线程去执行处理任务了.
关于Looper我们分析到这里,最后总结下Looper几个比较重要的API.
- Looper.prepare(): 创建looper
- Looper.loop(): 开启消息循环
- Looper.quit/quitSafely: 立即退出/安全退出
- 当looper退出后,通过handler发送消失会失败,send方法会返回false.
handler工作原理
通过前面对MessageQueue与Looper的了解,我们可以用一句话总结出三者关系:"Handler依赖Looper(获取当前线程的Looper),而Looper则依赖于MessageQueue(实例化Looper时会同时实例化一个MessageQueue)"
1. handler 准备阶段
我们知道Handler依赖于当前线程的Looper,而在主线程我们并没有手动创建looper,其实在主线程启动时也就是ActivityThread,已经初始化了一个looper,并且开启了消息循环.
对应源码
public static void main(String[] args) { //...省略部分代码 final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId()); TrustedCertificateStore.setDefaultUserDirectory(configDir); Process.setArgV0(""); //创建Looper Looper.prepareMainLooper(); ActivityThread thread = new ActivityThread(); thread.attach(false); 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"); }复制代码
如上源码,一切准备工作都以就绪,我们就可以尽情使用handler了.
2. handler 发送阶段
当我们创建Handler时,会检查当前线程是否包含Looper.
对应源码
public Handler(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 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; }复制代码
如果准备工作一切都没问题,那么就可以使用handler发送消息了.
对应源码
//通过Send发送普通消息public final boolean sendMessage(Message msg){ return sendMessageDelayed(msg, 0);}//通过Post发送Runnable消息public final boolean post(Runnable r){ return sendMessageDelayed(getPostMessage(r), 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=handler. msg.target = this; if (mAsynchronous) { msg.setAsynchronous(true); } return queue.enqueueMessage(msg, uptimeMillis);}复制代码
从上面源码可知,无论是Send还是Post,最终都是通过send方法将消息发送出去,并且发送消息仅仅往消息队列中插入了一条消息而已.
3. handler 处理阶段
当我们往消息队列中插入一条消息时,此时looper从MessageQueue中获取到新消息,就进入消息处理阶段.调用了handler的dispatchMessage方法进行处理.
对应源码
public void dispatchMessage(Message msg) { if (msg.callback != null) {//说明是一个Post消息 //callback为POST方法传递的Runnable对象 handleCallback(msg); } else {//说明是一个普通消息 if (mCallback != null) { //mCallback是个接口,提供一个创建时不需要派生handler子类.参考构造方法 if (mCallback.handleMessage(msg)) { return; } } //回调自身的handleMessage方法 handleMessage(msg); } }复制代码
最后我们对Hanlder流程做一个总结.
-
handler 准备阶段
- 线程启动时,Looper.prepare() 创建一个Looper,通过ThreadLocal将Looper对象和当前线程绑定.
- Looper.loop() 方法开启消息循环,不断从MessageQueue的中读取消息,如没有消息,则处于阻塞状态.
-
handler 发送阶段
-
当Handle创建时,会获得当前线程相关的Looper对象.
-
当通过Handle发送消息时,无论是Post还是Send普通消息,仅仅加入一条消息到MessageQueue.
-
looper通过MessageQueue的next方法获取新消息后,然后处理这个消息,最终looper会交由Handler的dispatchMessage方法.
-
-
handler 处理阶段
-
如果是Post消息,则回调Runnable的run方法.
-
如果是普通消息,则回调mCallback的handleMessage或自身的HandleMessage方法.
-
三. 在自定义Thread中使用hanlder
此外通过以上流程分析,我们可以知道如果在某些特殊情况需要在子线程使用handler.那么只需要为其线程创建looper,开启消息循环.这样再其他地方发送的消息都将在此线程中执行.
示例代码
//伪代码 new Thread(){ @Override public void run() { Looper.prepare(); Handler handler = new Handler(); Looper.loop(); } }.start();复制代码
四. Handler机制的扩展
为了更加方便使用Handler,Androi系统提供了两种方式.具体使用笔记简单就不讲述了,直接看源码.
- Activity.runOnUiThread(Runnable)
对应源码
public final void runOnUiThread(Runnable action) { if (Thread.currentThread() != mUiThread) { //发送Post消息 mHandler.post(action); } else { //直接执行任务 action.run(); }}复制代码
- View.post(Runnable)
对应源码
public boolean post(Runnable action) { final AttachInfo attachInfo = mAttachInfo; if (attachInfo != null) { //直接通过handler发送Post消息 return attachInfo.mHandler.post(action); } //先加入队列,等attachInfo被赋值时,会通过handler发送消息. getRunQueue().post(action); return true; }复制代码
最后用一张Handler工作原理图结束本文.
由于本人技术有限,如有错误的地方,麻烦大家给我提出来,本人不胜感激,大家一起学习进步.
参考链接: