说起Handler,对于android开发的人员都应该不会陌生。我们经常使用Handler来更新UI线程。
比如,我们在一个界面中使用了下拉刷新,然后由于android不允许我们在UI线程中联网(android2.3后),所以我们必须重新开启一个子线程来执行一些网络操作。当我们执行完网络操作的时候就需要反过来更新UI线程。所以这个时候Handler就为我们提供了方便的跨线程操作。
说了这么多其实Handler的作用就是用来将一个任务切换到某个指定的线程中去执行。
我们说Android中的消息机制,其是主要指的是Handler Looper MessageQueue这三者。因为我们需要打交道的主要是Handler。所以可能会忽略其他的两者。但是正是由于这三者才构成整个消息机制。
下面借用一个图来表示这三者之间的关系。
从上面的图中我们可以知道Handler的作用就是将一个Message挂载到另外的一个线程中的MessageQueue中去。然后Looper就会循环从MessageQueue中取出Message然后进行处理。
我们来给出一下简单的例子,然后根据这个例子来分析一下Handler的工作机制。
我们的这个例子就是在主线程中通过Handler来发送一下消息来通知子线程。
public class LooperThreadActivity extends Activity{
/** Called when the activity is first created. */
private final int MSG_HELLO = 0;
private Handler mHandler;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new CustomThread().start();//新建并启动CustomThread实例
findViewById(R.id.send_btn).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {//点击界面时发送消息
String str = "hello";
Log.d("Test", "MainThread is ready to send msg:" + str);
mHandler.obtainMessage(MSG_HELLO, str).sendToTarget();//发送消息到CustomThread
}
});
}
class CustomThread extends Thread {
@Override
public void run() {
//建立消息循环的步骤
Looper.prepare();//1、初始化Looper
mHandler = new Handler(){//2、绑定handler到CustomThread实例的Looper对象
public void handleMessage (Message msg) {//3、定义处理消息的方法
switch(msg.what) {
case MSG_HELLO:
Log.d("Test", "CustomThread receive msg:" + (String) msg.obj);
}
}
};
Looper.loop();//4、启动消息循环
}
}
}
接下来我们就来分步奏来分析一下其中发生的一些事情。
一、Handler将Message挂载到另外的线程上面去。
我们来分析一下Handler如何将一个Message挂载到另一个线程的MessageQueue上去。
上面的例子我们是通过obtainMessage 加 sendToTarget来发送消息的。其实也一样。
最终调用的都会是handler的sendMessage方法。下我们一起来看一下代码:
public final boolean sendMessage(Message msg)
{
return sendMessageDelayed(msg, 0);
}
public final boolean sendMessageDelayed(Message msg, long delayMillis)
{
if (delayMillis < 0) {
delayMillis = 0;
}
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
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);
}
我们可以看到我们调用的最后是调用了sendMessageAtTime方法。其中又调用了enqueueMessage(Queue queue ,Message msg,long time)
其中这个方法就是将我们的msg插入到queue中。并且将当前Handler放置到msg里面,用于处理msg。
而这个queue是哪里来的呢?
我们接着看代码:
这个queue其实也就是属性mQueue。
public Handler(Callback callback, boolean async) {
.....
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;
}
在构造方法中我们可以看到这个mQueue是由mLooper取决的。那么这个mLooper又是如何得到的呢?
我们来看一下Looper中的myLooper方法。
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
我们可以看到其中调用了sThreaLocal的get()方法。那么这个sThreadLocal是什么呢?他就是一个ThreadLocal类。其中保存着所有线程的信息。并且我们可以通过get方法获得本线程中的Looper对象。(在方法内部会自动判断并找出当前线程)。
也就是说我们得到了当前线程的Looper,Queue。也就是子线程的Looper ,Queue。
然后我们就向其中插入对应的信息。
好了说到这里,思路应该清晰了许多。我们在主线程中通过调用子线程中的handler对象的sendMessage方法。handler会通过TheadLocal查找出handler所在线程(子线程)的MessageQueue,并且将消息插入到队列中去。
二、Looper 的准备与执行。
我们都知道在子线程中如果想要使用handler的话就需要先生成一个looper。也就是调用Looper.prepare方法。接下来我们就来看一下prepare方法的实现。
public static void prepare() {
prepare(true);
}
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));
}
我们可以看到prepare方法中使用了ThreadLocal来查找当前线程中是否有Looper,如果没有的话就为当前线程创建一个Looper。
而在Looper的构造方法中又创建了一个MessageQueue。
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
好了Looper已经准备好了,这个时候我们就需要调用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.recycleUnchecked();
}
}
loop的工作原理主要就是不断地从MessageQueue中取消息。上面就是一个死循环。循环中调用queue.next()得到一个Message,如果这个Message不为空的话就调用Hanlder的dispatchMessage方法来处理事件。
这个时候我们会有疑问,如果遇到queue为空的话那不就会退出循环了吗?
Message next() {
......
for (;;) {
........
synchronized (this) {
// Try to retrieve the next message. Return if found.
final long now = SystemClock.uptimeMillis();
Message prevMsg = null;
Message msg = mMessages;
if (msg != null && msg.target == null) {
// Stalled by a barrier. Find the next asynchronous message in the queue.
do {
prevMsg = msg;
msg = msg.next;
} while (msg != null && !msg.isAsynchronous());
}
if (msg != null) {
if (now < msg.when) {
// Next message is not ready. Set a timeout to wake up when it is ready.
nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
} else {
// Got a message.
mBlocked = false;
if (prevMsg != null) {
prevMsg.next = msg.next;
} else {
mMessages = msg.next;
}
msg.next = null;
if (DEBUG) Log.v(TAG, "Returning message: " + msg);
msg.markInUse();
return msg;
}
} else {
// No more messages.
nextPollTimeoutMillis = -1;
}
// Process the quit message now that all pending messages have been handled.
if (mQuitting) {
dispose();
return null;
}
// If first time idle, then get the number of idlers to run.
// Idle handles only run if the queue is empty or if the first message
// in the queue (possibly a barrier) is due to be handled in the future.
if (pendingIdleHandlerCount < 0
&& (mMessages == null || now < mMessages.when)) {
pendingIdleHandlerCount = mIdleHandlers.size();
}
if (pendingIdleHandlerCount <= 0) {
// No idle handlers to run. Loop and wait some more.
mBlocked = true;
continue;
}
.......
}
...........
}
}
从上面的代码我们可以看出,在MessageQueue的next中,有一个死循环,如果一旦消息为null的时候mBlocked就会被标志为true。然后就陷入了死循环中,直到有消息插入后才将mBlocked置为false。
并且从上面我们也可以看到我们可以调用MessageQueue中的quit方法来终止死循环。
void quit(boolean safe)
所以到这里我们就知道了loop的工作原理了。有一个需要注意的就是我们调用Looper.loop方法后,该方法后面的代码需要等到我们调用Looper的quit方法才能够执行到。不然的话由于前面有个死循环,所以一直都无法执行了。而我们调用了quit方法后,线程就会执行完后后面的代码后消失。这点需要注意一下。
好了,现在我们说的都是子线程的Looper,我们在使用的时候UI线程是不需要使用Looper.prepare方法和Looper.loop方法的。其实在UI主线程中默认已经调用了这两个方法了。
我们可以查看ActivityThread.java
路径\frameworks\base\core\java\android\app\ActivityThread.java
public static void main(String[] args) {
......
Looper.prepareMainLooper();
ActivityThread thread = new ActivityThread();
thread.attach(false);
if (sMainThreadHandler == null) {
sMainThreadHandler = thread.getHandler();
}
AsyncTask.init();
if (false) {
Looper.myLooper().setMessageLogging(new
LogPrinter(Log.DEBUG, "ActivityThread"));
}
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
这个Main方法就是我们的主线程了。
好了,到这里我们就分析完了Looper和MessageQueue的工作原理。配合上上面讲的Handler的跨线程挂载消息的工作原理。我们应该能够比较好地理解笔记开头的那个示意图了。
三、执行Message。
上面我们分析到了loop循环中调用的msg.target.dispatchMessage方法。来处理这个message。
这个target就是一个Handler。那么这个handler是从哪里来的呢?
原来Handler将消息挂到当前线程的时候也将自己传递到了Message中。所以Handler对象不仅负责着将消息"发到队列上",而且还负责处理对应的消息。我们来看一下这个dispatchMessage方法。
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
......
}
}, 5000);
具体的调用就是handleCallback。我们来看看这个方法。
private static void handleCallback(Message message) {
message.callback.run();
}
2、其次检查mCallBack接口是否为null如果不为null的话就调用这个接口。
那么这个mCallBack接口是什么呢?
public Handler(Callback callback) {
this(callback, false);
}
这个callBack接口就是我们实现的时候的接口。
mHandler = new Handler(){//2、绑定handler到CustomThread实例的Looper对象
public void handleMessage (Message msg) {//3、定义处理消息的方法
switch(msg.what) {
case MSG_HELLO:
Log.d("Test", "CustomThread receive msg:" + (String) msg.obj);
}
}
};
是不是很眼熟。
3、如果全部都没有的话就需要调用HandleMesage方法。
那么handleMessage是什么呢?
/**
* Subclasses must implement this to receive messages.
*/
public void handleMessage(Message msg) {
}
这是个空方法。也就是我们在extends Handler 派生出子类Handler的时候可以实现的一个接口。也就类似于我们的第二种情况。
四、总结:
好了。Handler的工作的原理就大概这个样子了。主要分为几个步奏。
1、线程调用Looper.parpare方法借用ThreadLocal来为当前线程初始化一个Looper(内含MessageQueue)
2、使用Looper.loop方法,让当前线程的Looper工作起来,不断地从MessageQueue中获取消息,如果获取不到的话就会阻塞住。我们可以调用Looper.quit方法来终结loop。
3、我们需要在当前线程中声明一个Handler并且实现其handleMessage方法。
4、在另一个线程中调用当前线程的handler的sendMessage方法。内部借助ThreadLoacal找到当前线程的MessageQueue然后插入Message等待looper的调用。