浅谈-Android-Handler,Android开发必须要会

33 阅读2分钟

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; }

image.gif

首先调用Looper.myLooper()

public static @Nullable Looper myLooper() { return sThreadLocal.get(); }

image.gif

获得当前的looper对象,通过looper拿到MessageQueue,就完成了handler和looper之间的关联

下面继续看handler的消息发送

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); }

image.gif

先获得当前的消息队列,如果队列为空就抛出异常,不为空,向消息队列中插入消息

private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) { msg.target = this; if (mAsynchronous) { msg.setAsynchronous(true); } return queue.enqueueMessage(msg, uptimeMillis); }

image.gif

插入消息之前就指定消息发送给谁(msg.target),默认情况下发送给自己的handler,然后把消息放入队列中,handler就完成了发送message到MessageQueue的过程

那么消息又是如何轮询的呢?

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(); } }

image.gif

通过myLooper()方法获取当前looper,进而获得当前的消息队列,然后通过MessageQueue的next方法获取消息,消息为空时返回,不为空时,调用handler的dispatchMessage(msg)方法,然后这个过程一直循环

public void dispatchMessage(Message msg) { if (msg.callback != null) { handleCallback(msg); } else { if (mCallback != null) { if (mCallback.handleMessage(msg)) { return; } } handleMessage(msg); } }

image.gif

首先查看msg.callback是否为空,不为空时去调用handleCallback(msg),这个方法在handler的构造方法中存在,可以实现消息的拦截;为空只就 

调用handleMessage(msg),这个方法都是大家熟悉的,不在描述,整体的handler的原理就描述到这。

总结

handler在Android中扮演的非常重要的角色,熟悉handler的原理,不仅在面试的时候有用,就连activity的生命周期也是通过handler发送消息,详细请看源码

【附】相关架构及资料

最后

写到这里也结束了,在文章最后放上一个小小的福利,以下为小编自己在学习过程中整理出的一个学习思路及方向,从事互联网开发,最主要的是要学好技术,而学习技术是一条慢长而艰苦的道路,不能靠一时激情,也不是熬几天几夜就能学好的,必须养成平时努力学习的习惯,更加需要准确的学习方向达到有效的学习效果。 由于内容较多就只放上一个大概的大纲,需要更及详细的学习思维导图的点击这里>Android IOC架构设计免费获取。 群内还有免费的高级UI、性能优化、架构师课程、NDK、混合式开发(ReactNative+Weex)微信小程序、Flutter全方面的Android进阶实践技术资料,并且还有技术大牛一起讨论交流解决问题。

image