今天开始复习Android的异步消息处理机制,我们先从最熟悉的Handler讲起,还是老套路,一步一步来吧。
1.概念
Android的消息机制的上层接口,通过发送和处理Message和Runnable对象来关联相对应的的线程MessageQueue;
(1)可以让对应的Message和Runnable在未来的某个时间点进行相应处理
(2)让自己想要处理的耗时操作放在子线程,让更新UI的操作放在主线程;
2.handler的使用方法:
(1)使用post(runnable)方法:(其内部其实也是调用sendMessageDelay()方法)
(A)创建一个Handler;
(B)建立runnable;
(C)把runnable Post出去;
(2)通过sendMessage方法:
(A)创建一个Handler,实现handleMessage()方法
(B)创建一个Message,通过new或者使用Message.Obtain()方法直接从MessageQueue中拿到message对象;
(C)调用handler.sendMessage()方法
3.handler的内部机制:
俗话说的好啊,一个好汉三个帮,android如此强大的Handler机制当然也有“帮手”了。
讲到Handler,肯定离不开Looper、MessageQueue、Message这三者和Handler之间的关系,下面简略地带过,详细自己可以查阅相关资料,或者查看源码,这样更方便大家深入学习。
每一个线程只有一个Looper,每个线程在初始化Looper之后,然后Looper会维护好该线程的消息队列,用来存放Handler发送的Message,并处理消息队列出队的Message。它的特点是它跟它的线程是绑定的,处理消息也是在Looper所在的线程去处理,所以当我们在主线程创建Handler时,它就会跟主线程唯一的Looper绑定,从而我们使用Handler在子线程发消息时,最终也是在主线程处理,达到了异步的效果。
那么就会有人问,为什么我们使用Handler的时候从来都不需要创建Looper呢?这是因为在主线程中,ActivityThread默认会把Looper初始化好,prepare以后,当前线程就会变成一个Looper线程。
MessageQueue是一个消息队列,用来存放Handler发送的消息。每个线程最多只有一个MessageQueue。MessageQueue通常都是由Looper来管理,而主线程创建时,会创建一个默认的Looper对象,而Looper对象的创建,将自动创建一个MessageQueue。其他非主线程,不会自动创建Looper。
消息对象,就是MessageQueue里面存放的对象,一个MessageQueue可以包括多个Message。当我们需要发送一个Message时,我们一般不建议使用new Message()的形式来创建,更推荐使用Message.obtain()来获取Message实例,因为在Message类里面定义了一个消息池,当消息池里存在未使用的消息时,便返回,如果没有未使用的消息,则通过new的方式创建返回,所以使用Message.obtain()的方式来获取实例可以大大减少当有大量Message对象而产生的垃圾回收问题。
正如上图所示的,handler在整个异步消息处理时,起到至关重要的作用,它有两个作用,一个是发送消息,另一个是处理消息,处理的是来自Looper的消息;
从handler源码中就可以看出,handler的构造方法,在一开始就创建了一个looper,然后looper创建了MessageQueue,
*/ 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; }
构造方法中的looper是怎么来的呢,它是通过Java中的ThreadLocal.get()方法获得的,ThreadLocal它有其自身的特点,当不同的线程对同一个ThreadLocal进行访问时,不管是它的get方法还是它的set方法,它们对其的操作都仅仅限于各自线程的内部,这就保证了每一个线程对应单独一个Looper;
public static @Nullable Looper myLooper() { return sThreadLocal.get(); }Looper对象是通过prepare方法来创建一个Looper,再将Looper设置给ThreadLocal
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)); }
此时handler,MessageQueue和和Looper就关联起来了,我们知道不论我们调用sendMessage还是post方法,都需要开启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 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 { msg.target.dispatchMessage(msg); end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis(); } finally { if (traceTag != 0) { Trace.traceEnd(traceTag); } } if (slowDispatchThresholdMs > 0) { final long time = end - start; if (time > slowDispatchThresholdMs) { Slog.w(TAG, "Dispatch took " + time + "ms on " + Thread.currentThread().getName() + ", h=" + msg.target + " cb=" + msg.callback + " msg=" + msg.what); } } 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有了大致的轮廓,首先,Looper通过prepare方法创建Looper,然后设置给ThreadLocal,再通过loop方法不断从消息队列中获取消息,然后分发消息,我们可以清晰的看到,loop方法最后调用了msg.target.dispatchMessage(msg)方法;
target是什么鬼?继续看
/*package*/ Handler target;
Message中的target其实就是一个Handler;所以,这时我们就惊奇的发现,绕了一圈,最终还是通过handler去把消息传递给消息队列,然后消息队列又将消息分发给handler来处理。这里就提现出上述的Handler的两个作用,一个是接收,发送消息,另一个就是处理消息;
看到这里,对Handler就有一个大致的轮廓了;
(1)Looper取出队头的Message;
(2)对应的Handler调用handlerMessage方法进行消息处理;
(3)处理完成后,还是返回到looper中,就形成的循环;
5.handler引起的内存泄漏:
(1)原因:handler非静态内部类持有外部类的匿名引用,导致外部类无法被回收;
(2)解决办法:handler内部持有外部Activity的弱引用,并把handler改为静态内部类,然后在onDestroy方法中调用handler的removeCallBack()方法