背景: Handler解决线程之间发送消息
解决的问题:
1:主线程不能执行耗时操作,ANR
2:子线程不能操作主线程的UI视图
写在前面, 首先需要明确涉及到了 4个类:
Handler的核心类:
Message: 对发送的消息的封装
MessageQueue: 消息队列,存放所有的消息
Looper: 可以循环读取消息(从MessageQueue中读取)
Handler: 处理消息,同时也是发送消息的
1. Message: 消息包装类, 并且包含一个target属性成员(Handler在发送它时Handler自己就被赋值: msg.target=handler)
Message msg = Message.obtain();
msg.obj ="hello,你好!";
handler.sendMessage(msg);
2. MessageQueue: 是由Looper创建, 它主要存放Message
3. Looper: 在本线程中保存Looper实例和MessageQueue实例, 它的loop方法在MessageQueue当中取Message
Looper类:
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mRun = true;
mThread = Thread.currentThread();
}
public static final void prepare() {
if (sThreadLocal.get() != null) {
throw new RuntimeException("Only one Looper may be created per thread");
}
sThreadLocal.set(new Looper(true));
}
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主要作用:
1. 与当前线程绑定,保证一个线程只会有一个Looper实例,同时一个Looper实例也只有一个MessageQueue。
2. loop()方法,不断从MessageQueue中去取消息,交给消息的target属性的dispatchMessage去处理。
还记得上面说的Message的target属性吧, 没错就是Handler调用了dispatchMessage, dispatchMessage是个什么鬼?下面看源码:
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
handleMessage(msg);这句就是关键所在, 对这个是要我们接收方重写的, 也就是处理消息
最后注意:
1 主线程必须要有 handler的引用(线程之间使用同一个handler)
2 主线程一启动就会创建主线程的looper: 调用Looper.prepare()和Looper.loop()方法