android-rk3399/frameworks/base/core/java/android/os/Handler.java
在新建Handler时,在调用Hander重载函数,源码如下:
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()); } } //通过threadLocal.get获取当前线程的Looper对象 mLooper = Looper.myLooper(); if (mLooper == null) { throw new RuntimeException( "Can't create handler inside thread that has not called Looper.prepare()"); } //获取MessageQueue对象 mQueue = mLooper.mQueue; mCallback = callback; mAsynchronous = async; }
Handler是如何和MessageQueue联系起来的?
通过Handler构造函数中的业务逻辑,可以看出先获取looper对象,然后获取looper对象中的MessageQueue对象,这样做的目的是在当前线程中维护一个MessageQueue对象。
使用此函数来发送消息,将消息放到MessageQueue的队尾。发送的消息将在handleMessage函数中接收
public final boolean sendMessage(Message msg) { return sendMessageDelayed(msg, 0); }
此函数用来发送只包含what值的消息。使用场景:当不需要传数据时,可以通过此函数发送一个what值,然后在handleMessage中判断message的what值来执行自己的业务逻辑。
/** * Sends a Message containing only the what value. * * @return Returns true if the message was successfully placed in to the * message queue. Returns false on failure, usually because the * looper processing the message queue is exiting. */ public final boolean sendEmptyMessage(int what) { return sendEmptyMessageDelayed(what, 0); }
handler中的所有send开头的发送消息都会最终执行到enqueueMessage函数。
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) { msg.target = this; if (mAsynchronous) { msg.setAsynchronous(true); } //调用messagequeue对象的enqueueMessage函数 return queue.enqueueMessage(msg, uptimeMillis); }
子类必须实现此函数来接收消息。也就在我们使用handler时需要在此函数中实现接收消息的业务逻辑。
/** * Subclasses must implement this to receive messages. */ public void handleMessage(Message msg) { }
至此handler的源码分析完毕,里面还有一些其它的函数,在此没有做说明。