handler機制是Android重要的多線程數(shù)據(jù)傳輸機制,所以想從源碼來解析這個機制。
一般使用
在Activity中
public class MainActivity extends AppCompatActivity {
Handler handler = new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
switch (msg.what){
case 1:
showToast((String) msg.obj);
break;
}
return false;
}
});
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = findViewById(R.id.btn_start);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new Thread(new Runnable() {
@Override
public void run() {
Message message = Message.obtain();
message.what = 1;
message.obj = "Handler機制";
handler.sendMessage(message);
}
}).start();
}
});
}
private void showToast(String content){
Toast.makeText(this,content,Toast.LENGTH_SHORT).show();
}
}
Handler機制
1 最基本的Message
Message兩種創(chuàng)建
- 直接構(gòu)造
Message message = new Message();
- 通過obtain()方法
/**
* Return a new Message instance from the global pool. Allows us to
* avoid allocating new objects in many cases.
*/
public static Message obtain() {
synchronized (sPoolSync) {
if (sPool != null) {
Message m = sPool;
sPool = m.next;
m.next = null;
m.flags = 0; // clear in-use flag
sPoolSize--;
return m;
}
}
return new Message();
}
注釋很清楚桑驱,從全局池返回一個Message實例,避免在很多情況下分配新對象
很重要的變量
Handler target;
Message next;
這兩個之后會用到
2 handler.sendMessage方法
public final boolean sendMessage(Message msg)
{
return sendMessageDelayed(msg, 0);
}
這些相關(guān)的sendMessage
方法最終會調(diào)用一個enqueueMessage
方法
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
這個方法中將Message
的target
賦值為handler
自己缕贡,并調(diào)用了MessageQueue.enqueueMessage
方法
3 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;
}
核心大概這些代碼曙强,其實就是一個單向鏈表
boolean enqueueMessage(Message msg, long when) {
//保證線程安全性
synchronized (this) {
msg.when = when;
Message p = mMessages;
//這個消息是第一個或這個消息無需延遲 或 這個消息延遲時間比第一個消息短
if (p == null || when == 0 || when < p.when) {
//把這個消息放到鏈表的頭
msg.next = p;
mMessages = msg;
} else {
//循環(huán)整個鏈表,直到結(jié)束或這個消息延遲時間比某一個消息短
// 1. 直到結(jié)束情況:把這個消息放到鏈表的末尾
// 2.這個消息延遲時間比某一個消息短: prev -> p 改為 prev -> msg -> p
Message prev;
for (;;) {
prev = p;
p = p.next;
if (p == null || when < p.when) {
break;
}
}
msg.next = p; // invariant: p == prev.next
prev.next = msg;
}
}
return true;
}
本質(zhì)上完成對于把你傳遞的消息跟之前的消息排序
4. Looper的loop方法(循環(huán)消息隊列)
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();
}
}
其實核心就干了一件事msg.target.dispatchMessage(msg);
public static void loop() {
final Looper me = myLooper();
final MessageQueue queue = me.mQueue;
for (;;) {
Message msg = queue.next(); // might block
if (msg == null) {
// No message indicates that the message queue is quitting.
return;
}
try {
msg.target.dispatchMessage(msg);
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
}
}
詭異的是這個和我們最開始Handler的實現(xiàn)的回調(diào)方法名并不是一樣的
5.Handler的handleMessage方法
原來最后是由dispatchMessage
方法調(diào)用的涎拉,其實也是因為兩種方式來實現(xiàn)handleMessage
瑞侮,一種通過匿名接口回調(diào)實現(xiàn),另外一種直接重寫handleMessage
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
一些疑問
Handler與Looper的關(guān)聯(lián)
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;
}
所以的構(gòu)造都會調(diào)用這個鼓拧,在這個里面調(diào)用獲取了mLooper和mQueue
Looper的創(chuàng)建
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
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));
}
通過ThreadLocal的特性半火,保證每個線程只存在一個Looper對象。
ThreadLocal是一個關(guān)于創(chuàng)建線程局部變量的類季俩。
通常情況下钮糖,我們創(chuàng)建的變量是可以被任何一個線程訪問并修改的。而使用ThreadLocal創(chuàng)建的變量只能被當(dāng)前線程訪問酌住,其他線程則無法訪問和修改店归。
而這個實在ActivityThread(并沒有繼承線程)中被調(diào)用prepareMainLooper
方法
public static void main(String[] args) {
...
Looper.prepareMainLooper();
...
Handler 為什么可以 post Runnable
其實就是Handler自己幫你把Runnable轉(zhuǎn)換成Message
private static Message getPostMessage(Runnable r) {
Message m = Message.obtain();
m.callback = r;
return m;
}
子線程展示Toast報錯的原因
很多人都以為子線程展示Toast是因為不在主線程,其實并不是酪我。
private static class TN extends ITransientNotification.Stub {
...
TN(String packageName, @Nullable Looper looper) {
...
if (looper == null) {
// Use Looper.myLooper() if looper is not specified.
looper = Looper.myLooper();
if (looper == null) {
throw new RuntimeException(
"Can't toast on a thread that has not called Looper.prepare()");
}
}
mHandler = new Handler(looper, null) {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case SHOW: {
IBinder token = (IBinder) msg.obj;
handleShow(token);
break;
}
case HIDE: {
handleHide();
// Don't do this in handleHide() because it is also invoked by
// handleShow()
mNextView = null;
break;
}
case CANCEL: {
handleHide();
// Don't do this in handleHide() because it is also invoked by
// handleShow()
mNextView = null;
try {
getService().cancelToast(mPackageName, TN.this);
} catch (RemoteException e) {
}
break;
}
}
}
};
}
}
因為Toast需要初始化一個Handler消痛,并且最后的show仍然是在Handler的回調(diào)執(zhí)行的
同理,子線程展示Dialog報錯也是因為這個
如果非要在子線程展示Toast,可以這樣
class LooperThread extends Thread {
public Handler mHandler;
public void run() {
Looper.prepare();
Toast.makeText(getApplicationContext(),"子線程展示Toast",Toast.LENGTH_SHORT).show();
Looper.loop();
}
}
但是不要這么做都哭,因為Looper會阻塞這個線程
主線程不會因為Looper.loop()里的死循環(huán)卡死
這里涉及線程秩伞,先說說說進程/線程,進程:每個app運行時前首先創(chuàng)建一個進程欺矫,該進程是由Zygote fork出來的纱新,用于承載App上運行的各種Activity/Service等組件。進程對于上層應(yīng)用來說是完全透明的汇陆,這也是google有意為之怒炸,讓App程序都是運行在Android Runtime。大多數(shù)情況一個App就運行在一個進程中毡代,除非在AndroidManifest.xml中配置Android:process屬性阅羹,或通過native代碼fork進程勺疼。
線程:線程對應(yīng)用來說非常常見,比如每次new Thread().start都會創(chuàng)建一個新的線程捏鱼。該線程與App所在進程之間資源共享执庐,從Linux角度來說進程與線程除了是否共享資源外,并沒有本質(zhì)的區(qū)別导梆,都是一個task_struct結(jié)構(gòu)體轨淌,在CPU看來進程或線程無非就是一段可執(zhí)行的代碼,CPU采用CFS調(diào)度算法看尼,保證每個task都盡可能公平的享有CPU時間片递鹉。
有了這么準(zhǔn)備,再說說死循環(huán)問題:
對于線程既然是一段可執(zhí)行的代碼藏斩,當(dāng)可執(zhí)行代碼執(zhí)行完成后躏结,線程生命周期便該終止了,線程退出狰域。而對于主線程媳拴,我們是絕不希望會被運行一段時間,自己就退出兆览,那么如何保證能一直存活呢屈溉?簡單做法就是可執(zhí)行代碼是能一直執(zhí)行下去的,死循環(huán)便能保證不會被退出抬探,例如子巾,binder線程也是采用死循環(huán)的方法,通過循環(huán)方式不同與Binder驅(qū)動進行讀寫操作驶睦,當(dāng)然并非簡單地死循環(huán)砰左,無消息時會休眠匿醒。但這里可能又引發(fā)了另一個問題场航,既然是死循環(huán)又如何去處理其他事務(wù)呢?通過創(chuàng)建新線程的方式廉羔。
真正會卡死主線程的操作是在回調(diào)方法onCreate/onStart/onResume等操作時間過長溉痢,會導(dǎo)致掉幀,甚至發(fā)生ANR憋他,looper.loop本身不會導(dǎo)致應(yīng)用卡死孩饼。
轉(zhuǎn)載Gityuan的知乎回答
也就是說looper本身不會,它只是分發(fā)消息竹挡。ANR只是出現(xiàn)在處理消息的時候(也就是我們觸摸屏幕等)
總結(jié)handler機制流程圖
最后整個機制可以用這個流程圖表示