1、handle能否在子线程中创建呢?
我们一般都是在用在主线程的,今天我们就由这个问题来引出android的消息机制,
下面看一个例子:
在我们的activity创建一个子线程,我们在子线程创建handler
会报如下错误:
怎么解决呢?
我们看下报错信息,意思就是:没有调用Looper.prepare()方法,是不能创建handle的。
接着,我们在创建handle之前调用Looper.prepare()方法,竟然不报错了,好奇怪!!
我们分析下源码为什么会报错:
跟进Handle构造:
我们可以看到无参构造调用二个参数构造:
看标记,里面判断Looper是否为空,如果为空是不是抛出刚才的异常啊,
这时候我们明白了,创建handle之前必须的有Looper对象。所以我们才需要在线程使用handle的时候,先拿到looper.
2、
这个问题我们搞明白了,我们先想下在UI线程为什么可以直接用handle,而不需要拿到looper(调用Looper.prepare()方法)呢?
好!我们看下UI线程相关的源码,就是ActivityThread类:
当你的App启动的时候会调用ActivityThread的main方法:
所以我们直接看main方法:
public static void main(String[] args) {
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");
SamplingProfilerIntegration.start();
// CloseGuard defaults to true and can be quite spammy. We
// disable it here, but selectively enable it later (via
// StrictMode) on debug builds, but using DropBox, not logs.
CloseGuard.setEnabled(false);
Environment.initForCurrentUser();
// Set the reporter for event logging in libcore
EventLogger.setReporter(new EventLoggingReporter());
// Make sure TrustedCertificateStore looks in the right place for CA certificates
final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
TrustedCertificateStore.setDefaultUserDirectory(configDir);
Process.setArgV0("<pre-initialized>");
//注意这里,该方法就是调用Looper.prepare()方法
Looper.prepareMainLooper();
ActivityThread thread = new ActivityThread();
thread.attach(false);
if (sMainThreadHandler == null) {
sMainThreadHandler = thread.getHandler();
}
if (false) {
Looper.myLooper().setMessageLogging(new
LogPrinter(Log.DEBUG, "ActivityThread"));
}
// End of event ActivityThreadMain.
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
//注意这里,开启loop循环
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
这样的话我们就不用手动去调用了,系统底层已经帮我调用了。
3、
接下来,我们正式开始讲我们的android消息机制源码流程:
上面我们已经把handle创建好了,接着就是发消息:
发消息有这几种方法:
除了sendMessageAtFrontOfQueue()方法,其他都是调用sendMessageAtTime()方法,你可以跟进去看下。
所以我们直接分析sendMessageAtTime()方法:
首先我们讲下:这两个参数msg就是消息,uptimeMillis就是系统开机到到现在时刻的毫秒值,如果你发的有延迟的话,就是再此基础上加上延迟时间
看标记方法,该方法就是把消息放到消息队列(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;
}
从上面方法的实现来看,主要操作是通过单链表的插入操作实现的
接着我们看下消息是怎么取出来的:
消息取出是通过next()方法的:
Message next() {
// Return here if the message loop has already quit and been disposed.
// This can happen if the application tries to restart a looper after quit
// which is not supported.
final long ptr = mPtr;
if (ptr == 0) {
return null;
}
int pendingIdleHandlerCount = -1; // -1 only during first iteration
int nextPollTimeoutMillis = 0;
for (;;) {
if (nextPollTimeoutMillis != 0) {
Binder.flushPendingCommands();
}
nativePollOnce(ptr, nextPollTimeoutMillis);
synchronized (this) {
// Try to retrieve the next message. Return if found.
final long now = SystemClock.uptimeMillis();
Message prevMsg = null;
Message msg = mMessages;
if (msg != null && msg.target == null) {
// Stalled by a barrier. Find the next asynchronous message in the queue.
do {
prevMsg = msg;
msg = msg.next;
} while (msg != null && !msg.isAsynchronous());
}
if (msg != null) {
if (now < msg.when) {
// Next message is not ready. Set a timeout to wake up when it is ready.
nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
} else {
// Got a message.
mBlocked = false;
if (prevMsg != null) {
prevMsg.next = msg.next;
} else {
mMessages = msg.next;
}
msg.next = null;
if (DEBUG) Log.v(TAG, "Returning message: " + msg);
msg.markInUse();
return msg;
}
} else {
// No more messages.
nextPollTimeoutMillis = -1;
}
// Process the quit message now that all pending messages have been handled.
if (mQuitting) {
dispose();
return null;
}
// If first time idle, then get the number of idlers to run.
// Idle handles only run if the queue is empty or if the first message
// in the queue (possibly a barrier) is due to be handled in the future.
if (pendingIdleHandlerCount < 0
&& (mMessages == null || now < mMessages.when)) {
pendingIdleHandlerCount = mIdleHandlers.size();
}
if (pendingIdleHandlerCount <= 0) {
// No idle handlers to run. Loop and wait some more.
mBlocked = true;
continue;
}
if (mPendingIdleHandlers == null) {
mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)];
}
mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers);
}
// Run the idle handlers.
// We only ever reach this code block during the first iteration.
for (int i = 0; i < pendingIdleHandlerCount; i++) {
final IdleHandler idler = mPendingIdleHandlers[i];
mPendingIdleHandlers[i] = null; // release the reference to the handler
boolean keep = false;
try {
keep = idler.queueIdle();
} catch (Throwable t) {
Log.wtf(TAG, "IdleHandler threw exception", t);
}
if (!keep) {
synchronized (this) {
mIdleHandlers.remove(idler);
}
}
}
// Reset the idle handler count to 0 so we do not run them again.
pendingIdleHandlerCount = 0;
// While calling an idle handler, a new message could have been delivered
// so go back and look again for a pending message without waiting.
nextPollTimeoutMillis = 0;
}
大家注意for (;;) {
...............
...............
}
这里是通过无限循环的方法取出消息的,如果消息队列没有消息,next方法就会一直阻塞到这里等着,如果有新消息,就取出,消息就会从单链表里remove掉。
这里从发消息—>取出消息就说完了:
Looper的实现:
Looper就是用来处理消息的,具体来说,它会不停的从MessageQueue里查看是否有消息,如果有就处理,否则阻塞在那里,
先看下Looper的构造:
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
它默认创建一个消息队列,
我们都知道当我使用handle的时候,我们需要一个Looper对象,也就是,调用Looper.prepare()方法,那它是怎么拿到Looper对象的呢,这里需要说下:
ThreadLocal类:它是一个线程内部的数据存储类,通过它可以在指定线程中存储数据,数据存储后,只能在指定线程获取数据。
举个例子:
public class Test {
private ThreadLocal<Boolean> mThreadLocal = new ThreadLocal<>();
public void test() {
new Thread(new Runnable() {
@Override
public void run() {
mThreadLocal.set(true);
mThreadLocal.get();
这里mThreadLocal =true;
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
mThreadLocal.get();
这里mThreadLocal =null;
}
}).start();
}
}
看到了把,虽然在不同的线程访问的同一个变量,但是我们拿到的数据是不一样的。
我们的Looper就是存储在这里的,看下面源码:
rivate 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循环是怎么实现的呢?
接着看源码:
实现循环的是Looper.loop()方法:
ublic 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
final Printer logging = me.mLogging;
if (logging != null) {
logging.println(">>>>> Dispatching to " + msg.target + " " +
msg.callback + ": " + msg.what);
}
final long traceTag = me.mTraceTag;
if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
}
try {
msg.target.dispatchMessage(msg);
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
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()这个方法就是从队列里面取出消息
这里的next()是一个阻塞操作,没有消息就等待,有消息就取出
当queue.next()返回null的时候,looper循环才会结束
for (;;) {
Message msg = queue.next(); // might block
if (msg == null) {
// No message indicates that the message queue is quitting.
return;
}
msg.target.dispatchMessage(msg);
注意这行代码:我们取出消息之后就会交给handle来处理,msg.target其实就是你发送消息的handle,也就是说他会调用handle的dispatchMessage(msg);
我们接着跟进 handle的dispatchMessage(msg)
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
handleMessage(msg)方法 是不是很熟悉,这里我们就从子线程发到主线程了
4
总结:
首先我们创建handle必须得到Looper对象,否则回报异常,我们通过Looper.prepare()方法获取Looper对象,进一步说就是去ThreadLocal存储类里面取Looper对象,如果没有就new Looper(),通过Looper.loop()方法开启消息轮询,然后我们使用handle发消息,这时候消息会发送到我们的消息队列,也就是执行MessageQueue的enqueueMessage()方法,Message放入MessageQueue里面,looper就会调用loop()方法,通过无限循环调用messageQueue.next()方法取出消息,知道该方法返回null,才会结束循环,取出消息后就会调用handle的dispatchMessage(msg) 方法,进一步交给handle的handleMessage()方法处理,这样我们的消息从发送到处理流程就结束了