我们经常会用handler接收异步线程的数据,然后进行ui刷新,或是其他逻辑操作。
其他代码的函数,如handler中的sendMessageAtTime等就请自行阅读吧。~
希望通过了解相关的操作,作为framework源码入门的阶梯。
handler主要涉及framework的三个类:
Handler,Looper,MessageQueue
1.handler的创建和初始流程。
Handler的主要创建如下:
handler又是如何取数据的呢?</pre>
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; }
public interface Callback { public boolean handleMessage(Message msg); }
public Handler(Callback callback) { this(callback, false); }
一般来说,创建handler时,使用new handler(this),然后复写handleMessage方法,从源码的角度就可以很清楚的看到handler创建和复写方法的流程。
在创建过程中,看一下下面这段代码。
我们再来看一下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;
* Class used to run a message loop for a thread. Threads by default do * not have a message loop associated with them; to create one, call * {@link #prepare} in the thread that is to run the loop, and then * {@link #loop} to have it process messages until the loop is stopped.
这时候可能会有疑问,在activity使用的时候,并没有prepare的操作啊。这里请先看一下looper的两个全局变量。
</pre><pre name="code" class="java"><span style="font-size:14px;"> static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>(); private static Looper sMainLooper; // guarded by Looper.class</span>
这里要看一下ThreadLocal这个类。下面是百度百科的结果,具体的用法可以自行搜索,JDK 1.2的版本中就提供java.lang.ThreadLocal,ThreadLocal为解决多线程程序的并发问题提供了一种新的思路。
使用这个工具类可以很简洁地编写出优美的多线程程序,ThreadLocal并不是一个Thread,而是Thread的局部变量。
通常情况下,在activity中使用handler是不需要创建looper的,因为在activity的创建过程中,
ActivityThread.java会使用 Looper.prepareMainLooper();创建一个主线程的looper,一般handler都是
在主线程中处理数据,就不需要初始化了。
在looper创建的时候,会初始化一个messagequeue.
private Looper(boolean quitAllowed) { mQueue = new MessageQueue(quitAllowed); mThread = Thread.currentThread(); }
MessageQueue.java
* Low-level class holding the list of messages to be dispatched by a * {@link Looper}. Messages are not added directly to a MessageQueue, * but rather through {@link Handler} objects associated with the Looper. * * <p>You can retrieve the MessageQueue for the current thread with * {@link Looper#myQueue() Looper.myQueue()}.MessageQueue(boolean quitAllowed) { mQuitAllowed = quitAllowed; mPtr = nativeInit(); }
nativeInit()的源码在:/frameworks/base/core/jni/android_os_MessageQueue.cpp,偶对C++不熟,就不搬门弄斧了。
关于messagequeue的处理可以参考下面这篇博文:http://blog.youkuaiyun.com/kesalin/article/details/377657072.handler的发送消息和接收消息。
public final Message obtainMessage(int what, Object obj) { return Message.obtain(this, what, obj); }
<pre name="code" class="java"> public static Message obtain(Handler h, int what, Object obj) { Message m = obtain(); m.target = h; m.what = what; m.obj = obj; return m; }
从上面的源码可以看到message发送消息的时候,实际上是在handler下创建一个message顺序链表。/** * Return a new Message instance from the global pool. Allows us to * avoid allocating new objects in many cases. */ public static Message obtain() { synchronized (sPoolSync) { if (sPool != null) { Message m = sPool; sPool = m.next; m.next = null; m.flags = 0; // clear in-use flag sPoolSize--; return m; } } return new Message(); }
在Looper loop会创建一个队列,依次从queue中取出数据。
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();
}
}
其他代码的函数,如handler中的sendMessageAtTime等就请自行阅读吧。~