一、什么是Handler
handler机制是Android系统中提供的一种消息处理机制,它主要的作用是用来帮助非ui线程更新ui界面。我们知道在非ui线程中,我们无法直接更新ui界面,此时我们便可以利用Handler这一机制来对UI进行更新。换一句话说我们可以通过Handler来实现跨线程的通信。
基本原理:在一个线程中,开启一个循环去不断的从消息队列里取出消息,如果存在消息,就对消息进行处理。而在另一个线程中,我们往需要通信线程的消息队列里发消息,这样就实现的跨线程的通信。
二、实现的原理
1.Looper
由上面的图可知,我们首先需要一个循环来不断的从消息队列了取消息,而这个功能就是Looper实现的。
我们知道,每一个程序都有一个入口,而Android程序的入口便是ActivityThread中的main方法。其实ActivityThread就是UI线程。我们查看ActivityThread原代码的时候会发现main方法中有一个 Looper.prepare()的方法和一个Looper.loop()的方法,我们跟进Looper去看一下。
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));
}
我们发现这个函数中进行了一个判断,判断是否存在Looper这个对象,如果为null则为当前线程set一个Looper对象进去。ThreadLocal在这里我们不细讲,你只要知道,此时设置进去的这个Looper是线程独立的。
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;
}
//不为空的时候处理消息
..............
msg.recycleUnchecked();
}
}
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
在loop()函数中,首先得到当前线程中的Looper。然后从这个Looper中会得到一个Messagequeue,看到这你应该明白了,这就是上面提到的存放消息的消息队列。然后进行for循环。不断的从queue 中取出消息。看到这我们就明白了,在主线程一直存在一个循环,而这个就是有looper完成的。
2.Messagequeue
在上面我们从Looper中得到了MessageQueue,在这里我可以告诉你,每一个Looper中都存在唯一一个MessageQueue,而每一个线程中又只存在一个Looper,所以对于线程来说,只要有Looper存在便就有MessageQueue存在,这个MessageQueue就是该线程的唯一一个消息队列,用来存放发过来的消息。
3.Handler
在使用Handler的时候,我们都需要初始化一个实例,一般的使用方法如下。
Handler mHandler=new Handler(){
@Override
//此函数需要你重写,来完成你收到消息后所需要执行的动作。
public void handleMessage(Message msg)
{
super.handleMessage(msg);
}
};
我们跟进Handler看看它的源码。
//无参构造函数
public Handler() {
this(null, false);
}
//所有构造函数最终都将执行下面这个构造函数
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 = asyn
}
这上述代码中我们发现,我们首先使用mLooper = Looper.myLooper()这个方法为Handler里面的Looper赋值。而此时Looper.myLooper()得到的便是当前线程中唯一的一个Looper。而后又通过mQueue = mLooper.mQueue获取当前线程唯一的一个MessageQueue来赋值给Handler中的Messagequeue。因此此时Handler中的Looper与Messagequeue都是线程中唯一的。
现在我们来完成一个简单的线程通信。
首先在线程A中开启一个线程B,将Handler传入进去
testThread thread=new testThread(mHandler);
thread.start();
在线程B中,将得到线程A传来的Handler,包括Handler中的Looper,以及Messagequeue。然后通过mHandler.sendMessage(message);来发消息,此时就将把消息发送到线程A中的Messagequeue中。
public class testThread extends Thread{
Handler mHandler;
public testThread(Handler handler){
mHandler=handler;
}
@Override
public void run()
{
super.run();
Message message=new Message();
message.arg1=17;
mHandler.sendMessage(message);
}
}
线程A在不断循环的从Messagequeue取消息,当线程B通过sendMessage发送消息后,线程A中Messagequeue便将有了新的消息,线程A取出消息,交给Handler去执行,最终就将执行handleMessage()函数中的代码,这样就实现了线程间的通信。
三、总结
回顾一下上面的流程
1.首先需要一个Looper实例,这个Looper实例是线程唯一的。在主线程中已经帮我们执行了Looper.prepare()这个方法,所以Looper已经存在。但是在其他线程中,并没有主动执行Looper.prepare()这个方法,所以我们需要自己去执行。并且开启Looper.loop()这个循环。
2.因为有了Looper,所以就有了messagequeue,looper.loop()会不断的从消息队列中去消息,如果消息存在,则执行。
3.声明一个Handler对象,并重写它的handleMessage()方法。在Handler的构造函数中,会首先得到当前线程中保存的Looper实例,进而与Looper实例中的MessageQueue想关联。
4.将Handler对象作为参数传递给其他线程,并在其他线程中发送消息,当前线程就会收到,从而执行handleMessage(),完成两个线程间的通信。
四、其他线程中使用Handler的注意事项
因为主线程中自己已经帮我们执行了Looper.prepare()和Looper.loop()这两个方法,所以我们不需要自己执行。但是其他线程中没有,所以我们需要自己执行。
public class testThread extends Thread{
Handler mHandler;
public testThread(){
Looper.prepare();
//注意Handler对象的声明一定要在Looper.prepare()后。
}
@Override
public void run()
{
super.run();
.........
.........
.........
Looper.loop();
}
}
五、Handler.post(new Runnable())
Handler.post(new Runnable())是另一种是用Handler的方式,在Runnable中的run方法,其实是执行在UI线程中(就是需要接受消息的线程)的。可以直接修改ui界面。
mHandler.post(new Runnable()
{
@Override
public void run()
{
mTxt.setText("run");
}
});
我们来看看.post代码,我们发现最终也将和sendmessage一样执行到sendMessageAtTime这个函数
private static Message getPostMessage(Runnable r) {
//将runnable对象传入message中,封装成一个带有runnable对象的message。
Message m = Message.obtain();
m.callback = r;
return m;
}
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);
}
然后调用enqueueMessage
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
//将当前的Handler对象设置为msg的target,这样可以知道这个message最终将由哪个handler来执行。
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
//将Message加入到消息队列
return queue.enqueueMessage(msg, uptimeMillis);
}
在取出消息,对消息进行处理的时候,会做一个判断。
public void dispatchMessage(Message msg) {
//这里将判断msg.callback是否为空,上面我们将runnable对象赋值进去,所以这里将不为空。
//执行callback回调,也就是我们的Runnable对象,所以是直接执行在UI线程中的。
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}