当前 its leak 示例 异步消息 了解 modifier supported 异步
前言
做过 Android 开发的同学都知道,不能在非主线程修改 UI 控件,因为 Android 规定只能在主线程中访问 UI ,如果在子线程中访问 UI ,那么程序就会抛出异常
android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy.
并且,Android 也不建议在 UI 线程既主线程中做一些耗时操作,否则会导致程序 ANR .如果我们需要做一些耗时的操作并且操作结束后要修改 UI ,那么就需要用到 Android 提供的 Handler 切换到主线程来访问 UI .因此,系统之所以提供 Handler,主要原因就是为了解决在子线程中无法访问 UI 的问题.
概述
要理解 Handler 消息机制原理 还需要了解几个概念:
UI 线程 主线程 ActivityThread
Message Handler 发送和处理的消息,由 MessageQueue 管理.
MessageQueue 消息队列,用来存放通过 Handler 发送的消息,按照先进先出执行,内部使用的是单链表的结构.
Handler 负责发送消息和处理消息.
Looper 负责消息循环,循环取出 MessageQueue 里面的 Message,并交给相应的 Handler 进行处理.
在应用启动时,会开启一个 UI 线程,并且启动消息循环,应用不停地从该消息列表中取出,处理消息达到程序运行的效果.
Looper 负责的就是创建一个 MessageQueue,然后进入一个无限循环体不断从该 MessageQueue 中读取消息,而消息的创建者就是一个或多个 Handler .
流程图如下:
下面结合源码来具体分析
Looper
Looper 比较重要的两个方法是 prepare() 和 loop()
先看下构造方法
Looper 在创建时会新建一个 MessageQueue
final MessageQueue mQueue;
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
通过 prepare 方法可以为 Handler 创建一个 Lopper,源码如下:
可以看到这里创建的 Looper 对象使用 ThreadLocal 保存,这里简单介绍下 ThreadLocal.
static final ThreadLocal < Looper > sThreadLocal = new ThreadLocal < Looper > ();
private static Looper sMainLooper; // guarded by Looper.class
public static void prepare() {
prepare(true);
}
private static void prepare(boolean quitAllowed) {
if (sThreadLocal.get() != null) {
//一个线程只能有一个looper
throw new RuntimeException("Only one Looper may be created per thread");
}
sThreadLocal.set(new Looper(quitAllowed));
}
public static void prepareMainLooper() {
prepare(false);
synchronized(Looper.class) {
if (sMainLooper != null) {
throw new IllegalStateException("The main Looper has already been prepared.");
}
sMainLooper = myLooper();
}
}
ThreadLocal 是一个线程内部的数据存储类,通过它可以在指定的线程中存储数据,数据存储以后,只有在指定线程中可以获取到存储的数据,对于其他线程来说则无法获取到数据,这样就保证了一个线程对应了一个 Looper,从源码中也可以看出
一个线程也只能有一个Looper
,否则就会抛出异常.
prepareMainLooper() 方法是 系统在 ActivityThread 中调用的.
由此可以看出,系统在创建时,会自动创建 Looper 来处理消息,所以我们一般在主线程中使用 Handler 时,是不需要手动调用 Looper.prepare() 的.这样 Handler 就默认和主线程的 Looper 绑定.
ActivityThread.java public static void main(String[] args) {
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");
SamplingProfilerIntegration.start();
//...省略代码
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);
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
当 Handler 绑定的 Looper 是主线程的 Looper 时,则该 Handler 可以在其 handleMessage 中更新 UI,否则更新 UI 则会抛出异常.
在开发中,我们可能在多个地方使用 Handler,所以又可以得出一个结论:
一个Looper可以和多个Handler绑定
,那么 Looper 是怎么区分 Message 由哪个 Handler 处理呢?
继续看源码 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
final Printer logging = me.mLogging;
if (logging != null) {
logging.println(">>>>> Dispatching to " + msg.target + " " +
msg.callback + ": " + msg.what);
}
final long slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;
final long traceTag = me.mTraceTag;
if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
}
final long start = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
final long end;
try {
msg.target.dispatchMessage(msg);
end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
if (slowDispatchThresholdMs > 0) {
final long time = end - start;
if (time > slowDispatchThresholdMs) {
Slog.w(TAG, "Dispatch took " + time + "ms on "
+ Thread.currentThread().getName() + ", h=" +
msg.target + " cb=" + msg.callback + " msg=" + msg.what);
}
}
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();// 回收消息
}
}
2~6 行 获取当前 Looper 如果没有则抛异常,有则获取消息队列 MessageQueue
所以如果我们在子线程中使用 Handler 则必须手动调用 Looper.prepare() 和 Looper.loop()
系统在代码中提供了示例代码
获取到 MessageQueue 后开启消息循环,不断从 MessageQueue 中取消息,无则阻塞,等待消息.有则调用 msg.target.dispatchMessage(msg) 处理消息.
class LooperThread extends Thread {
public Handler mHandler;
public void run() {
Looper.prepare();
mHandler = new Handler() {
public void handleMessage(Message msg) {
// process incoming messages here
}
};
Looper.loop();
}
}
msg.target 就是 Message 所属的 Handler,这个会再后面具体介绍 Handler 中会说明
所以上面的问题就可以回答了,Looper 不需要考虑怎么区分 Message 由哪个 Handler 处理,只负责开启消息循环接收消息并处理消息即可.处理完消息后会调用 msg.recycleUnchecked() 来回收消息.
那么开启消息循环后,可以停止吗?
答案是肯定的,Looper 提供了 quit() 和 quitSafely() 来退出.
可以看到实际上调用的是 MessageQueue 中的退出方法,具体会在 MessageQueue 中介绍.
public void quit() {
mQueue.quit(false);
}
public void quitSafely() {
mQueue.quit(true);
}
调用 quit() 会直接退出 Looper,而 quitSafely() 只是设定一个退出标记,然后把消息队列中的已有消息处理完毕后才安全地退出.在 Loooper 退出后,通过 Handler 发送消息会失败.如果在子线程中手动创建了 Looper ,则应在处理完操作后退出 Looper 终止消息循环.
到此 Looper 的源码分析就完了,我们来总结下 Looper 所做的工作:
被创建时与线程绑定,保证一个线程只会有一个 Looper 实例 ,并且一个 Looper 实例只有一个 MessageQueue
创建后,调用 loop( ) 开启消息循环,不断从 MessageQueue 中取 Message ,然后交给 Message 所属的 Handler 去处理,也就是 msg.target 属性.
处理完消息后,调用 msg.recycleUnchecked 来回收消息
Message 和 MessageQueue
Message 是线程通信中传递的消息,它有几个关键点
使用 what 来区分消息
使用 arg1,arg2,obj,data 来传递数据
参数 target,它决定了 Message 所关联的 Handler,这个在后面看 Handler 源码时会一目了然.
MessageQueue
MessageQueue 负责管理消息队列,通过一个单链表的数据结构来维护.
源码中有三个主要方法:
enqueueMessage 方法往消息列表中插入一条数据,
next 方法从消息队列中取出一条消息并将其从消息队列中移除
quit 方法退出消息列表,通过参数 safe 决定是否直接退出
next 方法
可以发现 next 方法是一个无限循环的方法,如果消息队列中没有消息,那么 next 方法会一直阻塞在这里.当有新消息到来时,next 方法会从中获取消息出来返回给 Looper 去 处理 ,并将其从消息列表中移除.
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;
}
//...省略代码
}
}
quit 方法
从 上述代码中可以看出,当 safe 为 true 时,只移除尚未触发的所有消息,对于正在处理的消息不做处理, 当 safe 为 false 时,移除所有消息.
void quit(boolean safe) {
if (!mQuitAllowed) {
throw new IllegalStateException("Main thread not allowed to quit.");
}
synchronized(this) {
if (mQuitting) {
return;
}
mQuitting = true;
if (safe) {
removeAllFutureMessagesLocked(); //移除尚未处理的消息
} else {
removeAllMessagesLocked(); //移除所有消息
}
// We can assume mPtr != 0 because mQuitting was previously false.
nativeWake(mPtr);
}
}
private void removeAllMessagesLocked() {
Message p = mMessages;
while (p != null) {
Message n = p.next;
p.recycleUnchecked();
p = n;
}
mMessages = null;
}
private void removeAllFutureMessagesLocked() {
final long now = SystemClock.uptimeMillis();
Message p = mMessages;
if (p != null) {
if (p.when > now) {
removeAllMessagesLocked(); // 移除尚未处理的消息
} else { // 正在处理的消息不做处理
Message n;
for (;;) {
n = p.next;
if (n == null) {
return;
}
if (n.when > now) {
break;
}
p = n;
}
p.next = null;
do {
p = n;
n = p.next;
p.recycleUnchecked();
} while ( n != null );
}
}
}
Handler
Handler 是我们使用最多的类,主要用来发送消息和处理消息.
先来看构造方法
构造方法主要有三个参数
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());
}
}
//获取当前线程的 Looper 实例,如果不存在则抛出异常
mLooper = Looper.myLooper();
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread that has not called Looper.prepare()");
}
//关联 Looper 中的 MessageQueue 消息队列
mQueue = mLooper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
public Handler(Looper looper, Callback callback, boolean async) {
mLooper = looper;
mQueue = looper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
looper 不传值则调用 Looper.myLooper( ) 获取当前线程的 Looper 实例;传值则使用,一般是在子线程中使用 Handler 时才传参数.
callback Handler 处理消息时的回调
async 是否是异步消息.这里和 Android 中的 Barrier 概念有关,当 View 在绘制和布局时会向 Looper 中添加了 Barrier(监控器),这样后续的消息队列中的同步的消息将不会被执行,以免会影响到 UI 绘制,但是只有异步消息才能被执行.所谓的异步消息也只是体现在这,async 为 true 时,消息还可以继续被执行,不会被推迟运行.
从源码中可看出,因为 UI 线程在启动时会自动创建 Looper 实例,所以一般我们在 UI 线程中使用 Handler 时不需要传递 Looper 对象.而在子线程中则必须手动调用 Looper.prepare 和 Looper.loop 方法,并传递给 Handler ,否则无法使用,这一点肯定有不少童鞋都遇到过.
在拿到 Looper 对象后,Handler 会获取 Looper 中的 MessageQueue 消息队列,这样就和 MessageQueue 关联上了.
关联上 MessageQueue ,接下来那我们就看下 Handler 是如何发送消息的.
Handler 发送消息方法很多,实际上最后都是调用的 enqueueMessage 方法,看图说话
主要看 enqueueMessage 方法
可以看到在发送消息时给 Message 设置了 target = this 也就是当前的 Handler 对象,并调用了 MessageQueue 的 enqueueMessage 方法,这样就把消息存在消息队列,然后由 Looper 处理了.
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);
}
童鞋们应该记得之前在讲 Looper 时,说到 Looper 开启消息循环后,会不断从 MessageQueue 中取出 Message,并调用 msg.target.dispatchMessage(msg) 来处理消息.
接下来,就来看看 Handler 是如何接收消息的也就是 dispatchMessage 方法
可以看出 Handler 接收消息,只是调用一个空方法 handleMessage 是不是有些眼熟呢,看下我们写过很多次的 Handler 代码
public interface Callback {
public boolean handleMessage(Message msg);
}
/**
* Subclasses must implement this to receive messages.
*/
public void handleMessage(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);
}
}
没错这就是我们自己创建 Handler 时重写的方法,由我们来处理消息,然后根据 msg.what 标识进行消息处理.
private Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case value:
break;
default:
break;
}
}
};
总结
应用启动时会启动 UI 线程也就是主线程 ActivityThread,在 ActivityThread 的 main 方法中会调用 Looper.prepareMainLooper() 和 Looper.loop () 启动 Looper .
Looper 启动时会创建一个 MessageQueue 实例,并且只有一个实例,然后不断从 MessageQueue 中获取消息,无则阻塞等待消息,有则调用 msg.target.dispatchMessage(msg) 处理消息.
我们在使用 Handler 时 需要先创建 Handler 实例,Handler 在创建时会获取当前线程关联的 Looper 实例 ,和 Looper 中的消息队列 MessageQueue.然后在发送消息时会自动给 Message 设置 target 为 Handler 本身,并把消息放入 MessageQueue 中,由 Looper 处理.Handler 在创建时会重写的
handleMessage 方法中处理消息.
如果要在子线程中使用 Handler 就需要新建 Looper 实例,传给 Handler 即可.
再看下流程图
最后
因篇幅较长,童鞋们的 Handler 肯定用的炉火纯青了,所以最后就不写例子了.
本人写博客不久,写的不好的地方,望童鞋们海涵.
Android Handler 消息机制原理解析
来源: http://www.bubuko.com/infodetail-2458315.html