做安卓开发我们都知道几下几点:
安卓规定主线程不能执行耗时操作,否则会出现ANR,因此我们执行一些耗时操作时都是在子线程中运行
子线程不能更新UI,只有主线程(UI线程)才能更新
为什么子线程不能更新UI呢?
因为安卓的主线程是非线程安全的,如果同时有多个线程同时去改UI,可能会发生预想不到的结果
有同学说给主线程上锁,更新UI的时候只允许一个线程工作不就好了吗,但是你想想这样做,我们的效率是不是变低了?会让UI访问的逻辑变得复杂,其次是会降低UI的访问频率。因此安卓引入了Handler**
安卓会对UI进行检测,判断是否是主线程。ViewRootImpl对UI的操作做了验证,这个验证工作是由ViewRootImpl的checkThread来完成的。
void checkThread() {
if (mThread != Thread.currentThread()) {
throw new CalledFromWrongThreadException(
"Only the original thread that created a view hierarchy can touch its views.");
}
}
安卓的消息机制包括几个概念
Handler
Message
Looper
MessageQueue
Android系统主要通过Message、MessageQueue、Looper、Handler来实现消息处理,其中Message代表消息,MessageQueue是用来描述消息队列,Looper是用来创建消息队列以及进入消息循环,Handler 是用来发送消息和处理消息。
当我们在主线程中创建Handler的时候会通过ThreadLocal去获取主线程的Looper进行绑定,主线程的Looper是在主线程创建时生成的,Looper中又包含了一个MessageQueue,主线程中Looper执行死循环不断的从MessageQueue获取消息。
当我们使用Handler发送消息时,Handler会拿到与它绑定的Looper对象的MessageQueue对象,然后往消息队列中插入一条消息,Looper拿到消息后再交由Handler处理
源码分析
1.Handler发送消息的流程
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);
}
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
//这里msg被加入消息队列queue
return queue.enqueueMessage(msg, uptimeMillis);
}
我们可以看到Handler发送消息的顺序是这样的:
sendMessage>sendMessageDelayed>sendMessageAtTime>enqueueMessage
在sendMessageAtTime()获取MessageQueue 对象(Hnadler在主线程创建的时候就会绑定主线程的MessageQueue ),然后条件符合执行enqueueMessage(),这个方法里面执行queue.enqueueMessage( ),就是往主线程的消息队列中插入一条消息
2.Looper的工作流程
主线程创建的时候也会创建Looper和MessageQueue ,并且还执行了Looper.loop()方法,这个方法会不断的去MessageQueue 获取消息
public static void loop() {
final Looper me = myLooper();
if (me == null) {
throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
}
//从Looper中取出消息队列
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);
}
//将消息交给target处理,这个target就是Handler类型
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();
}
}
我们可以看到loop方法有个死循环,一直调用 MessageQueue 的next()方法获取消息
for (;;) {
Message msg = queue.next(); // might block 这里会被阻塞,如果没有新消息
if (msg == null) {
// No message indicates that the message queue is quitting.
return;
}
当Handler发送消息过来后,Looper就会获取到,它把消息交给Handler处理
//将消息交给target处理,这个target就是Handler类型
msg.target.dispatchMessage(msg);
3.Handler处理消息的流程
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
//这个方法很简单,直接调用msg.callback.run();
handleCallback(msg);
} else {
//如果我们设置了callback会由callback来处理消息
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
//否则消息就由这里来处理,这是我们最常用的处理方式
handleMessage(msg);
}
}
if (msg.callback != null):当我们使用post方式的时候msg.callback =Runable对象, handleCallback(msg)中会调用msg.callback.run(),就是执行我们的回调方法
handler1.post(new Runnable() {
@Override
public void run() {
bTV.setText();
}
});
if (mCallback != null):当我们创建Handler的时候是使用Callback接口的时候执行
Handler handler1 = new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(@NonNull Message message) {
return true;
}
});
handleMessage(msg):就是我们使用匿名类创建Handler的方式就会执行
Handler handler2 = new Handler() {
@Override
public void handleMessage(@NonNull Message message) {
}
};
由此我们可以总结得到:
消息队列就像一个传送带,传送带本身是不会动的,message是传送带上的货物,Looper是发动机,发动机不断的滚动传送带把货物拿出来,即时没有货物发动机依然工作。Handler就是负责把货物放进传送带,并负责在另一端接收货物打包。