最近在项目里面频繁的使用到了handler 于是我开始好好的关注了一下这个知识点 下面我从我的理解的角度好好讲解一下Handler.*
从一个handler例子的报错开始 我们一步步的深入了解一下这个知识点
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
@SuppressLint("HandlerLeak")
public class MainActivity extends Activity {
private Handler mHandler;
private final int FLAG = 1;
private final String TAG = MainActivity.class.getSimpleName();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
handlerTest();
}
private void handlerTest() {
new Thread(new Runnable() {
public void run() {
mHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
if(msg.what == FLAG){
Log.e(TAG, "收到的消息为:--->>>"+msg.obj);
}
}
};
Message msg = new Message();
msg.what = FLAG;
msg.obj = "Hello Handler!!!";
mHandler.sendMessage(msg);
Looper.loop();
}
}).start();
}
}
上面的例子里面运行后可以看到如下的错误信息:
大家可以看到加红色边框的地方 提示我们调用Looper.prepare(). 那么我就在代码里面子线程的handler的实例化前面添加一句 Looper.prepare(); 运行之后发现代码果然不会报错了.
那么接下来 我们就逆推上去,一步一步的看一下这个Handler
Looper.prepare();
/** Initialize the current thread as a looper. * This gives you a chance to create handlers that then reference * this looper, before actually starting the loop. Be sure to call * {@link #loop()} after calling this method, and end it by calling * {@link #quit()}. */ 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)); }
看完上面的代码 我们可以看出:
1.1 这个方法初始化出了一个带有Looper的线程1.2 在这个方法之后需要调用loop()方法进行消息的轮询 想要停止消 息的轮询需要调用quit()方法.
1.3 异常提示: “Only one Looper may be created per thread” 表示一个线程只能创建一个Looper
1.4 初始化一个带有Looper的线程 从而将这个线程和属于它的Looper关联起来 这个体现就在 sThreadLocal.set(new Looper(quitAllowed)); 这句话里面 我们可以来看看Looper的构造方法:
private Looper(boolean quitAllowed) { mQueue = new MessageQueue(quitAllowed); mThread = Thread.currentThread(); }
这里我们可以看到:
1.4.1 在Looper的初始化过程中首先是初始化了一个MessageQueue
1.4.2 就是获得了当前的线程对象. 这里就能解释了当sThreadLocal.set(new Looper(quitAllowed))的时候将带当前的线程和属于他的Looper进行了绑定.
另外从另外一个方面也能看得出这一点:
在调用Looper.prepare()方法时先会使用if (sThreadLocal.get() != null)- 判断sThreadLocal中是否已经保存了Looper.
- 如果已经保存了Looper则会报错:Only one Looper may be created per thread.一个线程只能创建一个Looper
- 如果没有保存Looper,才会去调用sThreadLocal.set(new Looper());
- 这样就确保了当前线程和Looper的唯一对应.
但是我们可以说一个线程对应一个Looper,但是我们却不能说一个线程也对应一个Handler,因为一个线程是可以有多个Handler的,但是这多个Handler却是拥有共同的Looper,简单地说就是:一个线程,对应一个Looper,对应一个消息队列.
在平常使的MainActivity中的UI线程中使用Handler时并没有调用Looper.prepare(); 这是为什么呢?
因为UI线程是主线程,系统已经自动帮我们调用了Looper.prepare()方法.2.现在我们来讨论一下消息的发送和处理的具体流程,这边主要是用到了两个方法:
handler.sendMessage(message) —->发送消息
handleMessage(Message msg) —–>处理消息2.1 Handler发送消息的方式有很多,但是除了sendMessageAtFrontOfQueue(Message msg) 以外的几个方法最终会调用sendMessageAtTime(Message msg, long uptimeMillis)方法.
/** * Enqueue a message into the message queue after all pending messages * before the absolute time (in milliseconds) <var>uptimeMillis</var>. * <b>The time-base is {@link android.os.SystemClock#uptimeMillis}.</b> * Time spent in deep sleep will add an additional delay to execution. * You will receive it in {@link #handleMessage}, in the thread attached * to this handler. * * @param uptimeMillis The absolute time at which the message should be * delivered, using the * {@link android.os.SystemClock#uptimeMillis} time-base. * * @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. Note that a * result of true does not mean the message will be processed -- if * the looper is quit before the delivery time of the message * occurs then the message will be dropped. */ 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); } private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) { msg.target = this; if (mAsynchronous) { msg.setAsynchronous(true); } return queue.enqueueMessage(msg, uptimeMillis); }
从上面可以看出来: 2.1.1 在enqueueMessage(queue, msg, uptimeMillis)方法里面msg.target = this;中的this就是指的是当前的handler对象本身. 将消息放到了queue里面进行消息的处理<enqueueMessage(queue, msg, uptimeMillis)> 而这个enqueueMessage(queue, msg, uptimeMillis)方法里面有一个队列距离触发时间最短的message排在队列最前面,同理距离触发时间最长的message排在队列的最尾端. 若调用sendMessageAtFrontOfQueue()方法发送消息它会调用该enqueueMessage(msg, uptimeMillis) 来让消息入队只不过时间为延迟时间为0,即它会插入到队列头部.
这就是消息的入队操作,那么消息怎么出队呢?
这就要看Looper中的loop()方法
/**
* Run the message queue in this thread. Be sure to call
* {@link #quit()} to end the 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();
}
}
在该方法中是一个死循环for (;;),即Looper一直在轮询消息队列(MessageQueue)
在该方法中有两句代码很重要:
1 Message msg = queue.next();
queue.next()消息队列的出列.
2 msg.target.dispatchMessage(msg);
用调用msg里的target的dispatchMessage()方法.
target是什么呢?
参见上述sendMessageAtTime(Message msg, long uptimeMillis)可知:
target就是Handler!!!!在此回调了Handler的dispatchMessage方法,所以该消息就发送给了对应的Handler.
接下来看Handler的dispatchMessage(Message msg)方法:
/**
* Handle system messages here.
*/
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
其中涉及到的CallBack为:
public interface Callback {
public boolean handleMessage(Message msg);
}
Handler的其中一个构造方法为:
Handler handler=new Handler(callback);
所以在dispatchMessage(Message msg)涉及到了CallBack
在多数情况下message和Handler的callBack均为空
所以会调用dispatchMessage(Message msg)方法:
这就回到了我们最熟悉的地方.