1、概述:
大家都知道,在Android中,UI线程是不安全的,更新UI在UI线程中处理,其他耗时工作都不能在该线程执行,相信大家在面试的时候也知道Handler是面试官非常喜欢问的一个问题。同样我面试的也如此,每次面试前去复习不如写一遍博客记录下来更深刻。
2、Handler的简单使用:
private Handler handler = new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); } };
上面这样使用可能会引起内存泄露的风险,因为当使用内部类(匿名内部类)来创建Handler的时候,Handler隐式持有一个外部类对象(Activity)的引用,而Handler常伴有一个耗时的后台线程操作,当在后台线程访问过程中,Activity不再使用了,那么它就在特定情况下会被GC回收,但由于这时线程尚未执行完,而该线程持有Handler的引用(不然它怎么发消息给Handler?),这个Handler又持有Activity的引用,就导致该Activity无法被回收(即内存泄露),直到网络请求结束(例如图片下载完毕)。(摘自:https://www.cnblogs.com/xujian2014/p/5025650.html)。今天这篇不是写该内容的解决方式,具体的解决方案就看这篇文章吧。
3、Looper消息循环:
Handler的发送的消息发送到哪里,由谁来承载,由谁来发出呢。
Handler发送的消息都发送到MessageQueue,而MessageQueue由Looper创建,进入一个无限循环不断从该MessageQueue读取消息并回调处理。
根据上面的描述,我们先来看看Looper的源码,对于Looper主要有prepare()和loop()两个方法;
我们经常会在当前线程调用Looper.prepare()和Looper.loop(),首先来看看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)); }
我们实际会调用的是Looper的有参构造函数,sThreadLocal是一个ThreadLocal对象,可以在一个线程中存储变量,我们可以看到sThreadLocal.set(new Looper(quitAllowed))函数往该对象中存储了一个Looper对象,并在前面判断该get()方法是否为空,不为空则抛出异常,该异常相信大家都见到过,在同一个线程内调用多次prepare()方法,这就说明了Looper.prepare()方法不能被调用两次,同时也保证了一个线程中仅有一个Looper对象。
下面我们看Looper的构造方法:
private Looper(boolean quitAllowed) { mQueue = new MessageQueue(quitAllowed); mThread = Thread.currentThread(); }
构造方法创建了一个MessageQueue(消息队列),同时变量mThread指向当前线程;
好的,上面我们看完了Looper.prepare()的源码,我们再来看看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(); // 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); } 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; try { msg.target.dispatchMessage(msg); dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0; } finally { 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(); } }
看源码,我们可以看到Looper对象是通过myLooper()方法获取的,该方法也就是上面prepare()方法中说过的sThreadLocal对象调用get()方法获取到存入进去的Looper对象。绕不绕口绕不绕口我就问你,我都差点没明白,看下面,就是如此简单。
public static @Nullable Looper myLooper() { return sThreadLocal.get(); }
1、MessageQueue queue = me.mQueue获取到该消息队列;
2、在循环体for(;;)中进入我们前面所说的无限循环;
3、Message msg = queue.next()获取消息,没有消息则返回;
4、msg.target.dispatchMessage(msg)把消息给msg.target处理,msg.tartget其实就是发送该msg的Handler对象,解析到Handler的时候就会看到;
总结:Looper两个静态方法,一个是prepare(),一个是loop(),prepare()方法主要是绑定当前线程,创建一个Looper对象,且当前线程唯一,同时也创建了一个MessageQueue(消息队列);loop()方法主要是
循环消息队列中的Message,并交给msg的target属性处理。
4、Handler解析:
通常我们使用Handler的时候都会new一个Handler对象,我们来看看Handler的构造函数;
public Handler() { this(null, false); } 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 " + Thread.currentThread() + " that has not called Looper.prepare()"); } mQueue = mLooper.mQueue; mCallback = callback; mAsynchronous = async; }
同样,调用的依然是有参构造函数,在if(mLooper == null)里抛出的异常就是我们经常能遇到的,现在看本质这个异常其实就是当前线程Looper对象为null,我们通常解决就是在该线程中调用Looper.prepare()
和Looper.loop()方法;mQueue = mLooper.mQueue获取到Looper对象中的消息队列,那么我们的Handler就跟MessageQueue消息队列关联上了。
OK,Handler我们知道是如何构造的了,我们看看我们常用的sendMessage(Message msg)方法是如何工作的,ctrl+左键进去看看源码:
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); }
很明显,是调用的这些方法。sendMessageAtTime(Message msg, long uptimeMillis)方法判断了MessageQueue(消息队列)对象是否null;重点来了,enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis)
中的msg.target = this,刚刚我们提到的,将msg给msg.target属性处理,我们这里能看到,msg.target指向了this,也就是我们的Handler,所以前面说的,msg.target属性其实就是当前消息的Handler对象,那么前面的流程就是looper
循环处理MessageQueue(消息队列),获取到消息就给发送该消息的Handler对象的dispatchMessage()方法处理;
so,我们来看看dispatchMessage()方法是如何处理的:
public void dispatchMessage(Message msg) { if (msg.callback != null) { handleCallback(msg); } else { if (mCallback != null) { if (mCallback.handleMessage(msg)) { return; } } handleMessage(msg); } }
该方法很简单,就是判断msg的callback是否为null,不为null,则执行该回调,否则执行handleMessage(msg)方法,我们使用sendMessage()方法的时候,是没有给到callback的,那么我们就是调用handleMessage()方法,看看该方法实现了什么:
/** * Subclasses must implement this to receive messages. */ public void handleMessage(Message msg) { }
handleMessage(Message msg)是一个空方法,没错,该方法是由我们自己实现的,上面我们创建的Handler对象实现了handlerMessage(Message msg)方法,就是调用的我们自己实现的这个方法。
什么时候会调用handleCallback(Message msg)方法呢,其实handler.post(new Runnable{})就是回调的我们这个方法,看看 post(Runnable run) 方法的源码吧:
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); }
我们可以看到,post方法其实还是调用了我们前面所看到的sendMessageDelayed()方法,不同的是,我们处理了一下传进来的Runnable对象,我们看看getPostMessage(r)方法:
private static Message getPostMessage(Runnable r) { Message m = Message.obtain(); m.callback = r; return m; }
这里我们创建了一个Message对象,该对象的callback属性指向我们传进来的Runnable对象,so,前面我们看到的判空部分,handleCallback(Message msg) 那么就会执行,
private static void handleCallback(Message message) { message.callback.run(); }
所以,Runnable其实不是一个新的线程在工作,只是作为一个回调实现;
总结:
整个异步消息处理流程其实并不复杂,明白他们之间的关系就很容易理解,我来画个图更好的理解下这整个流程:
Ok,大概就是这样理解的,网上大佬们的解析也很多,借鉴了很多大佬的语言描述,感激不尽。这里只是简单记录我对知识的理解,如有错误请指出。