android源码解析-异步消息
android异步消息中我们常用的就是如下方式
先创建一个handler实例:
private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
//处理message返回结果
};
接着开启一个线程:
new Thread(new Runnable() {
@Override
public void run() {
handler.sendEmptyMessage(2);
}
}).start();
我们执行了handler.sendEmptyMessage();
方法,但是在主线程接到了返回结果,下面我们来探究一下原因.
原因探究
我们先看Handler.class
的构造方法
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 = async;
}
构造方法创建了Looper的实例和MessageQueue的引用对象.创建了Looper的实例也就找到了线程对应的looper和MessageQueue,因为一个MessageQueue对应的只有一个Looper.中间有一句mLooper = Looper.myLooper();
我们稍后再看.
接下来看Handler调用的sendMessage方法。你会发现所有的方法调用的都是sendMessageAtTime()
方法,那我们就看一下sendMessageAtTime()
方法吧:
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);
}
Handler的sendMessageAtTime()
调用了queue.enqueueMessage()
方法也就是messageQueue的入队方法。
我们看一下enqueueMessage:
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
我们看到handler把自己的实例放进了msg的target这个到后边会用到,接下来看MessageQueue类的enqueueMessage()
方法:
boolean enqueueMessage(Message msg, long when) {
if (msg.target == null) {
throw new IllegalArgumentException("Message must have a target.");
}
if (msg.isInUse()) {
throw new IllegalStateException(msg + " This message is already in use.");
}
synchronized (this) {
if (mQuitting) {
IllegalStateException e = new IllegalStateException(msg.target + " sending message to a Handler on a dead thread");
Log.w(TAG, e.getMessage(), e);
msg.recycle();
return false;
}
msg.markInUse();
msg.when = when;
Message p = mMessages;
boolean needWake;
if (p == null || when == 0 || when < p.when) {
// New head, wake up the event queue if blocked.
msg.next = p;
mMessages = msg;
needWake = mBlocked;
} else {
// Inserted within the middle of the queue. Usually we don't have to wake
// up the event queue unless there is a barrier at the head of the queue
// and the message is the earliest asynchronous message in the queue.
needWake = mBlocked && p.target == null && msg.isAsynchronous();
Message prev;
for (;;) {
prev = p;
p = p.next;
if (p == null || when < p.when) {
break;
}
if (needWake && p.isAsynchronous()) {
needWake = false;
}
}
msg.next = p; // invariant: p == prev.next
prev.next = msg;
}
// We can assume mPtr != 0 because mQuitting is false.
if (needWake) {
nativeWake(mPtr);
}
}
return true;
}
里边的for循环就是把消息放到messagequeue里的方法,根据when时间顺序.
至此handler就把sendmessage中的message发送到messagequeue中.其中判断了之前我们定义到msg里的handler实例.
那么MessageQueue是在哪里维护的呢?
看上边的Handler构造方法我们发现mQueue = mLooper.mQueue;
这个行代码.
也就是说MessageQueue是在Looper维护的.
首先看一下Looper.prepare()
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));
}
再看一下构造方法:
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
实际上在子线程必须执行Looper.prepare()
是因为需要通过sThreadLocal.set(new Looper(quitAllowed));
建立Lopper与sThreadLocal的关系.我们再回看Handler的构造方法mLooper = Looper.myLooper();
这个方法.
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
我们看到直接return了sThreadLocal.get()
这就说明了为什么要执行Looper.prepare()
,因为需要先建立和sThreadLocal的关系.
接下来看 Looper.loop();
方法是执行从enqueueMessage取出消息.
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();
}
}
有一个死循环执行queue.next()
方法.如果有消息就继续执行.然后执行消息分发msg.target.dispatchMessage(msg);
,可以看到msg.target
就是我们最开始在enqueueMessage步骤把handler.如果没消息就休息等待.
下面看一下dispatchMessage:
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
最后分发完方法后执行了handleMessage回调方法.handleMessage方法我们再熟悉不过了.就是我们new Handler创建的回调.
总结
Handler通过初始化创建了Looper和实例化了MessageQueue,Looper创建的时候需要先执行Looper.propar()
,通过handler构造方法匹配了本地ThreadLocal和线程-Looper-MessageQueue三者的对应关系.
handler通过sendMessage方法执行MessageQueue的enqueueMessage()
方法,实现了往MessageQueue插入消息.
由Looper.loop()
方法从MessageQueue中取出消息.由for循环执行queue.next()
方法,然后执行Handler的消息分发msg.target.dispatchMessage(msg);
,也就是我们new Handler的回调方法.
一些题外话
android中启动关于线程和线程间通信的方法有很多,万变不离其宗,这里就简单的讲下:
1.关于Handler.post()
(1)Handler.post();
,这个方法的常用场景是我们在子线程完成,子线程中,调用post()
方法后可以再方法内写ui操作的东西,,切记不要在子线程实例化的Handler执行post()
再操作UI,举个例子在其他子线程1实例化的Handler,在子线程2执行post()
操作ui,那么还会报错告诉你"工作线程不能操作UI"的错误.
(2)这个方法的实现原理并不是新开启线程或者怎么样,原理还是异步消息,把Handler封装到Message里作为传递然后跨线程执行.具体请看源码,由于不太复杂们这里就不贴了.
2.关于HandlerThread
HandlerThread handlerThread = new HandlerThread("HandlerThread");
handlerThread.start();
Handler handler_thread = new Handler(handlerThread.getLooper(), new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
//线程内耗时操作
return false;
}
});
handler_thread.sendEmptyMessage();
源码解析
(1)当执行handlerThread.start();
方法时候,执行了HandlerThread
的run()
方法,里边执行了Looper.prepare();
和Looper.loop();
,又是熟悉的配方.在这一步建立了Looper/MessageQueue/threadLocal之前的关系,并且执行了Looper.loop()
方法,线程处于阻塞状态。当我们发送一个消息的时候就会被执行。
3.关于IntentService:
(1)继承自Service,它可以理解为就是一个Service,只不过融合了HandlerThread。
(2)继承IntentService创建自己的服务的时候会重写onHandleIntent()
方法,因为这个方法就是在IntentService源码中Handler的handleMessage()
里实现的方法。
(3)源码在onCreate()
中实现了HandlerThread并且执行了start方法,然后new了ServiceHandler对象。
(4)在onStart()
中发送消息。
(5)在onStartCommand()
中调用了onStart()
方法。
(6)总结:这样整个过程就通了,onCreate()
创建HandlerThread,每次启动服务都会调用onStartCommand()
也就实现了发送消息。然后onHandleIntent()
回调处理线程耗时操作。
网友评论