Looper类是Android中一个重要的类,用于处理Android线程方面的应用。它的主要作用是初始化MessageQueen,分配消息。描述如下
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 prepare() in the thread that is to run the loop,
and then loop() to have it process messages until the loop is stopped.
Most interaction with a message loop is through the Handler class.
这是一个为线程运行消息循环的类。默认情况下,新建线程是没有消息循环的(主线程除外),可以通过创建一个Looper对象,调用Looper.prepare()方法来启动一个消息循环。
Looper类的源代码非常简单
private static final String TAG = "Looper";
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
private static Looper sMainLooper;
final MessageQueue mQueue;
final Thread mThread;
volatile boolean mRun;
private Printer mLogging;
private static Looper mMainLooper = null;
sThreadLocal:线程本地化的变量,当使用ThreadLocal维护变量时,ThreadLocal为每个使用该变量的线程提供独立的副本,每一个线程都可以独立的改变自己的副本而不影响其他线程的副本,从而避免了竞争关系。
mQueue:消息队列。
mThread:与该Looper有关的线程。
mRun:判断线程是否开始,该变量为volatile修饰,线程每次使用该对象时,都会重新读取变量修改后的值。
mMainLooper:主线程Looper。
Looper.prepare()
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mRun = true;
mThread = Thread.currentThread();
}
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));
}
在构造函数中初始化了MessageQueen,和线程,prepare函数设置了sThreadLocal。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
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.recycle();
}
}
这是Looper类中最重要的一个方法,首先先取出Looper对象,取出MessageQueen对象,然后在循环中用dispatchMessage来处理消息(此时target对象就是Handler),将消息不断的发送出去给相应的handler处理。