在Android系统中,每一个App的主线程即UI线程如果做过多耗时操作会引发ANR(Application Not Responding),我们可以通过Handler+Looper+Message将耗时操作放到子线程处理,处理完成后,如果需要主线程处理结果,则通过handler将处理结果发送到主线程,那么这里的传递机制是怎么样的呢?
在开始正文前先来介绍两个Handler的使用方法,一个是可以正常执行的,一个是不可以正常执行的,至于原因我们会在后面讲解。
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
// TODO: 15/05/2017 handle the message
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
new Thread() {
@Override
public void run() {
Message message = handler.obtainMessage();
message.arg1 = 1;
handler.sendMessage(message);
}
}.start();
常见的Handler机制大概是这样一个流程,当然这个可以正常执行。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
new Thread() {
@Override
public void run() {
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
// TODO: 15/05/2017 handle the message
}
};
Message message = handler.obtainMessage();
message.arg1 = 1;
handler.sendMessage(message);
}
}.start();
}
这个不可以正常执行,并且会crash,报错信息如下
E/AndroidRuntime: FATAL EXCEPTION: Thread-11532
Process: com.sundroid.helloworld, PID: 20125
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
at android.os.Handler.<init>(Handler.java:200)
at android.os.Handler.<init>(Handler.java:114)
at com.sundroid.helloworld.Main2Activity$1$1.<init>(Main2Activity.java:19)
at com.sundroid.helloworld.Main2Activity$1.run(Main2Activity.java:19)
下面我们结合源代码对该流程进行简单的分析。
android.os.Handler.java
public Handler() {
this(null, false);
}
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());
}
}
//获取当前的loop,如果为空就抛出异常,这里的报错信息是不是很熟悉?
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;
}
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);
}
android.os.MessageQueue.java
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;
}
android.os.Looper.java
public static @Nullable Looper myLooper() {
//获取和当前线程的Looper对象。sThreadLocal保证对象在一个线程中的唯一性
return sThreadLocal.get();
}
private static void prepare(boolean quitAllowed) {
//如果sThreadLocal已经存在Looper了,如果再prepare就会报错,也就是说一个线程中只能有一个looper对象。
if (sThreadLocal.get() != null) {
throw new RuntimeException("Only one Looper may be created per thread");
}
//创建looper并且保存在sThreadLocal中
sThreadLocal.set(new Looper(quitAllowed));
}
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;
//确保此线程的标识是本地进程的标识,并跟踪该标识实际上是什么。
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 {
//这里的target是发送消息的Handler
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();
}
}
贴了这个多代码,感觉写了好多,哈哈,下面按照惯例贴个图来总结下这个流程。
简单的总结下就是整个机制就是通过ThreadLocal保证了变量在线程中的唯一性,looper死循环不断从MessageQueue中取Message,如果Message不为空,则通过Message中的Handler对象将消息进行分发到拥有Looper对象的线程中。
我们现在来解决一个问题就是上面发送消息错误的写法。正确的写法是怎么样的呢?
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
new Thread() {
@Override
public void run() {
Looper.prepare();
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
// TODO: 15/05/2017 handle the message
}
};
Message message = handler.obtainMessage();
message.arg1 = 1;
handler.sendMessage(message);
Looper.loop();
}
}.start();
}
只需在Handler创建之前调用Looper.prepare()之后调用 Looper.loop()就可以了。
那么有的同学就该好奇了,那么第一种写法并没有看到这样调用啊,怎么就正常的运行了,有这个疑问的同学都是好同学,其实这里是有创建的,在哪呢?
答案是ActivityThread。
ActivityThread管理应用进程的主线程的执行(相当于普通Java程序的main入口函数),并根据AMS的要求(通过IApplicationThread接口,AMS为Client、ActivityThread.ApplicationThread为Server)负责调度和执行activities、broadcasts和其它操作。
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.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");
}
对于这块内容笔者会在后面进行介绍,第一次在这儿写博客,如果有些的不当的地方,还请各位看官不吝赐教,阿里嘎多。