在Android系統(tǒng)中份名,每一個App的主線程即UI線程如果做過多耗時操作會引發(fā)ANR(Application Not Responding),我們可以通過Handler+Looper+Message將耗時操作放到子線程處理,處理完成后际歼,如果需要主線程處理結(jié)果扔傅,則通過handler將處理結(jié)果發(fā)送到主線程剑梳,那么這里的傳遞機制是怎么樣的呢苗傅?
在開始正文前先來介紹兩個Handler的使用方法,一個是可以正常執(zhí)行的缸浦,一個是不可以正常執(zhí)行的夕冲,至于原因我們會在后面講解。
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機制大概是這樣一個流程裂逐,當然這個可以正常執(zhí)行歹鱼。
@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();
}
這個不可以正常執(zhí)行,并且會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)
下面我們結(jié)合源代碼對該流程進行簡單的分析弥姻。
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已經(jīng)存在Looper了,如果再prepare就會報錯颠悬,也就是說一個線程中只能有一個looper對象矮燎。
if (sThreadLocal.get() != null) {
throw new RuntimeException("Only one Looper may be created per thread");
}
//創(chuàng)建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();
//死循環(huán)
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是發(fā)送消息的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();
}
}
貼了這個多代碼诞外,感覺寫了好多,哈哈灾票,下面按照慣例貼個圖來總結(jié)下這個流程峡谊。
簡單的總結(jié)下就是整個機制就是通過ThreadLocal保證了變量在線程中的唯一性,looper死循環(huán)不斷從MessageQueue中取Message刊苍,如果Message不為空既们,則通過Message中的Handler對象將消息進行分發(fā)到擁有Looper對象的線程中。
我們現(xiàn)在來解決一個問題就是上面發(fā)送消息錯誤的寫法正什。正確的寫法是怎么樣的呢啥纸?
@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創(chuàng)建之前調(diào)用Looper.prepare()之后調(diào)用 Looper.loop()就可以了。
那么有的同學就該好奇了婴氮,那么第一種寫法并沒有看到這樣調(diào)用啊斯棒,怎么就正常的運行了盾致,有這個疑問的同學都是好同學,其實這里是有創(chuàng)建的荣暮,在哪呢庭惜?
答案是ActivityThread。
ActivityThread管理應(yīng)用進程的主線程的執(zhí)行(相當于普通Java程序的main入口函數(shù))渠驼,并根據(jù)AMS的要求(通過IApplicationThread接口蜈块,AMS為Client、ActivityThread.ApplicationThread為Server)負責調(diào)度和執(zhí)行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");
}
對于這塊內(nèi)容筆者會在后面進行介紹,第一次在這兒寫博客蜓席,如果有些的不當?shù)牡胤狡饕唬€請各位看官不吝賜教,阿里嘎多厨内。