安卓的異步消息處理機(jī)制就是handler機(jī)制孩灯。
主線程,ActivityThread被創(chuàng)建的時(shí)候就會(huì)創(chuàng)建LooperLooper被創(chuàng)建的時(shí)候創(chuàng)建MessageQueue碉怔。也就是說(shuō)主線程會(huì)直接或簡(jiǎn)介創(chuàng)建出來(lái)Looper和MessageQueue烘贴。具體創(chuàng)建解釋,參考:
Android異步消息處理機(jī)制完全解析撮胧,帶你從源碼的角度徹底理解
Handler的工作機(jī)制簡(jiǎn)單來(lái)說(shuō)是這樣的
1桨踪、Handler發(fā)送消息僅僅是調(diào)用MessageQueue的enqueueMessage向插入一條信息到MessageQueue
2、Looper不斷輪詢調(diào)用MeaasgaQueue的next方法
3芹啥、如果發(fā)現(xiàn)message就調(diào)用handler的dispatchMessage馒闷,ldispatchMessage被成功調(diào)用,接著調(diào)用handlerMessage()
1叁征、Handler的鐵三角—— Handler纳账、MessageQueue和Lopper
android的消息機(jī)制就是指Handler機(jī)制,Handler機(jī)制的運(yùn)行需要MeeageQueue和Looper的輔助捺疼。
注意: 我們常常用Handler來(lái)更新UI疏虫,但是不是說(shuō)Handler就是把用來(lái)更新UI的,我們的耗時(shí)的I/O操作啤呼,讀取文件卧秘,訪問(wèn)網(wǎng)絡(luò)等等都是可以在Handler里面操作的
2、MessageQueue(消息隊(duì)列)的工作原理
MessageQueue中文翻譯就是消息隊(duì)列官扣,它內(nèi)部存儲(chǔ)了一組信息翅敌,存放的是Message,以隊(duì)列的形式對(duì)外提供了插入和刪除的工作(雖然名字叫做隊(duì)列惕蹄,但是其內(nèi)部的 存儲(chǔ)結(jié)構(gòu)是單鏈表)
主要 插入 和 讀取 兩個(gè)操作蚯涮,這兩個(gè)操作對(duì)應(yīng)著兩個(gè)方法:
插入(入隊(duì)) enqueueMessage(Message msg, long when)
讀戎巫ā(出隊(duì)) next()
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方法
next方法在這里是一個(gè)無(wú)限循環(huán)的方法,如果消息隊(duì)列里面沒(méi)有消息遭顶,那么他就會(huì)處于阻塞狀態(tài)张峰,當(dāng)有新的消息到來(lái)的時(shí),next就會(huì)返回這條消息并且將其從單鏈表中移除棒旗。
Message More ...next() {
128 // Return here if the message loop has already quit and been disposed.
129 // This can happen if the application tries to restart a looper after quit
130 // which is not supported.
131 final long ptr = mPtr;
132 if (ptr == 0) {
133 return null;
134 }
135
136 int pendingIdleHandlerCount = -1; // -1 only during first iteration
137 int nextPollTimeoutMillis = 0;
138 for (;;) {
139 if (nextPollTimeoutMillis != 0) {
140 Binder.flushPendingCommands();
141 }
142
143 nativePollOnce(ptr, nextPollTimeoutMillis);
144
145 synchronized (this) {
146 // Try to retrieve the next message. Return if found.
147 final long now = SystemClock.uptimeMillis();
148 Message prevMsg = null;
149 Message msg = mMessages;
150 if (msg != null && msg.target == null) {
151 // Stalled by a barrier. Find the next asynchronous message in the queue.
152 do {
153 prevMsg = msg;
154 msg = msg.next;
155 } while (msg != null && !msg.isAsynchronous());
156 }
157 if (msg != null) {
158 if (now < msg.when) {
159 // Next message is not ready. Set a timeout to wake up when it is ready.
160 nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
161 } else {
162 // Got a message.
163 mBlocked = false;
164 if (prevMsg != null) {
165 prevMsg.next = msg.next;
166 } else {
167 mMessages = msg.next;
168 }
169 msg.next = null;
170 if (false) Log.v("MessageQueue", "Returning message: " + msg);
171 return msg;
172 }
173 } else {
174 // No more messages.
175 nextPollTimeoutMillis = -1;
176 }
177
178 // Process the quit message now that all pending messages have been handled.
179 if (mQuitting) {
180 dispose();
181 return null;
182 }
183
184 // If first time idle, then get the number of idlers to run.
185 // Idle handles only run if the queue is empty or if the first message
186 // in the queue (possibly a barrier) is due to be handled in the future.
187 if (pendingIdleHandlerCount < 0
188 && (mMessages == null || now < mMessages.when)) {
189 pendingIdleHandlerCount = mIdleHandlers.size();
190 }
191 if (pendingIdleHandlerCount <= 0) {
192 // No idle handlers to run. Loop and wait some more.
193 mBlocked = true;
194 continue;
195 }
196
197 if (mPendingIdleHandlers == null) {
198 mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)];
199 }
200 mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers);
201 }
202
203 // Run the idle handlers.
204 // We only ever reach this code block during the first iteration.
205 for (int i = 0; i < pendingIdleHandlerCount; i++) {
206 final IdleHandler idler = mPendingIdleHandlers[i];
207 mPendingIdleHandlers[i] = null; // release the reference to the handler
208
209 boolean keep = false;
210 try {
211 keep = idler.queueIdle();
212 } catch (Throwable t) {
213 Log.wtf("MessageQueue", "IdleHandler threw exception", t);
214 }
215
216 if (!keep) {
217 synchronized (this) {
218 mIdleHandlers.remove(idler);
219 }
220 }
221 }
222
223 // Reset the idle handler count to 0 so we do not run them again.
224 pendingIdleHandlerCount = 0;
225
226 // While calling an idle handler, a new message could have been delivered
227 // so go back and look again for a pending message without waiting.
228 nextPollTimeoutMillis = 0;
229 }
230 }
3喘批、Looper的工作原理
Looper中文翻譯是輪詢器或者消息泵或者循環(huán)。個(gè)人還是叫做輪詢器比較形象一些铣揉。
3.1饶深、Looper的作用
Looper是一個(gè)輪詢器,它的作用不斷輪詢MessageQueue逛拱,當(dāng)如果有新的消息就交給Handler處理敌厘,如果輪詢不到新的消息,那就自身就處于阻塞狀態(tài)橘券。
3.2额湘、Looper的構(gòu)造函數(shù)創(chuàng)建了MessageQueue
我們通過(guò)查看Loop而這個(gè)類卿吐,可以發(fā)現(xiàn)的他的構(gòu)造方法里面創(chuàng)建了一個(gè)MessageQueue旁舰,然后將當(dāng)前線程的對(duì)象保存起來(lái)
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
3.3、new Handler的hanlder不能沒(méi)有Looper
new出來(lái)一個(gè)Handler但是沒(méi)有創(chuàng)建Looper的話就會(huì)報(bào)錯(cuò)嗡官。
"Can't create handler inside thread that has not called Looper.prepare()"); 箭窜,
解決辦法就是new Handler的時(shí)候加上Looper.prepare();
如下代碼中,如果handler2加上Looper.prepare();沒(méi)有就會(huì)報(bào)錯(cuò)
public class MainActivity extends Activity {
private Handler handler1;
private Handler handler2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
handler1 = new Handler();
new Thread(new Runnable() {
@Override
public void run() {
Looper.prepare();
handler2 = new Handler();
}
}).start();
}
}
3.4衍腥、主線程(ActivityThread)磺樱,被創(chuàng)建的時(shí)候就會(huì)創(chuàng)建一個(gè)Looper
線程默認(rèn)是沒(méi)有Looper的,但是為什么在主線程沒(méi)有創(chuàng)建的Looper就可以使用Handler婆咸?主線程是特別的竹捉。主線程,也就是ActivityThread尚骄,主線程被創(chuàng)建的時(shí)候就會(huì)創(chuàng)建一個(gè)Looper块差,這點(diǎn)是比較特殊的,也正因?yàn)檫@點(diǎn)倔丈,所以我們?cè)谥骶€程創(chuàng)建了Handler就直接能用了憨闰。
3.5、Looper的ThreadLocal
Looper有一個(gè)特殊的概念需五,那就是ThreadLocal鹉动,(他并不是線程),他的作用是幫助Handler獲得當(dāng)前線程的Looper(多個(gè)線程可能有多個(gè)Looper)
Looper 的幾個(gè)方法
創(chuàng)建:
Looper.prepare() : 為當(dāng)前線程創(chuàng)建一個(gè)Looper
prepareMainLooper() : UI線程(ActivityThread)創(chuàng)建Looper的開(kāi)啟:
Looper.loop() : 開(kāi)啟消息輪詢退出
quit() : 直接退出Looper
quitSafely() : 設(shè)定一個(gè)標(biāo)記宏邮,只有當(dāng)目前已有消息處理完畢之后才會(huì)執(zhí)行退出操作泽示。
注意:當(dāng)Looper退出后缸血,Handler就無(wú)法發(fā)送消息,send出去的消息會(huì)返回false边琉;當(dāng)我們?cè)谧泳€程中創(chuàng)建了Looper并且所有的消息都處理完畢的時(shí)候属百,要記得調(diào)用 quit 方法,不讓這個(gè)Looper就一直處于阻塞狀態(tài)一直那么等待下去
Looper這個(gè)類里面最重要的方法就是loop()開(kāi)啟消息循環(huán)這個(gè)方法了变姨,看一下代碼:
Run the message queue in this thread. Be sure to call quit() to end the loop.
108
109 public static void More ...loop() {
110 final Looper me = myLooper();
111 if (me == null) {
112 throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
113 }
114 final MessageQueue queue = me.mQueue;
115
116 // Make sure the identity of this thread is that of the local process,
117 // and keep track of what that identity token actually is.
118 Binder.clearCallingIdentity();
119 final long ident = Binder.clearCallingIdentity();
120
121 for (;;) {
122 Message msg = queue.next(); // might block
123 if (msg == null) {
124 // No message indicates that the message queue is quitting.
125 return;
126 }
127
128 // This must be in a local variable, in case a UI event sets the logger
129 Printer logging = me.mLogging;
130 if (logging != null) {
131 logging.println(">>>>> Dispatching to " + msg.target + " " +
132 msg.callback + ": " + msg.what);
133 }
134
135 msg.target.dispatchMessage(msg);
136
137 if (logging != null) {
138 logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
139 }
140
141 // Make sure that during the course of dispatching the
142 // identity of the thread wasn't corrupted.
143 final long newIdent = Binder.clearCallingIdentity();
144 if (ident != newIdent) {
145 Log.wtf(TAG, "Thread identity changed from 0x"
146 + Long.toHexString(ident) + " to 0x"
147 + Long.toHexString(newIdent) + " while dispatching to "
148 + msg.target.getClass().getName() + " "
149 + msg.callback + " what=" + msg.what);
150 }
151
152 msg.recycleUnchecked();
153 }
154 }
通過(guò)代碼我們知道:looper方法是一個(gè)死循環(huán)族扰,唯一跳出的循環(huán)的方式是MessageQueue的next方法返回null,但是基本上是不可能的定欧。如果我們不手動(dòng)調(diào)用quit或者quitSafely方法的話渔呵,MessageQueue的next方法是不可能返回null的。
因?yàn)楫?dāng)MessageQueue沒(méi)有消息時(shí)砍鸠,next方法會(huì)一直阻塞在那里扩氢,因?yàn)镸essageQueue的next方法阻塞了,就導(dǎo)致Looper的loop方法也一直在阻塞了爷辱。
這里我們那一分為二的談录豺,
- loop輪詢不到消息:那么處于阻塞狀態(tài),然后就沒(méi)有然后了饭弓,除了又輪詢到了新的消息
- loop輪到了新的消息:Looper就會(huì)處理消息
1双饥、msg.target.dispatchMessage(msg),這里的 msg.targe就是指Handler對(duì)象
2弟断、一圈下來(lái)咏花,Handler發(fā)送的消息有交給了自己的dispatchMessage方法來(lái)處理了。(這個(gè)dispatchMessage方法不是Handler自己調(diào)用時(shí)阀趴,是與Handler相相關(guān)的Looper簡(jiǎn)介調(diào)用的)昏翰,這樣下來(lái),就成功地將邏輯切換到指定的線程當(dāng)中去了
4刘急、Handler的工作原理
4.1棚菊、Handler主要工作
主要工作:消息的 發(fā)送 和 接受 。
4.2叔汁、Handler消息發(fā)送的形式
先附上兩份最簡(jiǎn)單的日常正常使用post和send方式的代碼
send方式sendEmptyMessage方法的小demo
public class MainActivity extends Activity {
private static final int MSG_CHANGE_TEXT = 0x2001;
private TextView mTv;
private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what){
case MSG_CHANGE_TEXT:
mTv.setText("send方式修改的文字");
break;
}
}
};;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTv= (TextView) findViewById(R.id.mTv);
mTv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
handler.sendEmptyMessage(MSG_CHANGE_TEXT);
}
});
}
}
post方式的postDelayed方法的小demo
public class MainActivity extends Activity {
private Handler handler;
private TextView mTv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
handler = new Handler();
mTv = (TextView) findViewById(R.id.mTv);
mTv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
change();
}
});
}
private void change(){
new Thread(new Runnable() {
@Override
public void run() {
handler.postDelayed(new Runnable() {
@Override
public void run() {
mTv.setText("啊哈哈哈");
}
},300);
}
}).start();
}
}
兩種形式统求,post和send
其實(shí)post最終還是會(huì)調(diào)用send
Handler的部分post和send的源碼
post部分
我們發(fā)現(xiàn),5個(gè)關(guān)于post的方法里面攻柠,調(diào)來(lái)調(diào)去就是3個(gè)方法
sendMessageDelayed
sendMessageAtTime
sendMessageAtFrontOfQueue (postAtFrontOfQueue方法一家獨(dú)有)
public final boolean post(Runnable r)
{
return sendMessageDelayed(getPostMessage(r), 0);
}
public final boolean postAtTime(Runnable r, long uptimeMillis)
{
return sendMessageAtTime(getPostMessage(r), uptimeMillis);
}
public final boolean postAtTime(Runnable r, Object token, long uptimeMillis)
{
return sendMessageAtTime(getPostMessage(r, token), uptimeMillis);
}
public final boolean postDelayed(Runnable r, long delayMillis)
{
return sendMessageDelayed(getPostMessage(r), delayMillis);
}
public final boolean postAtFrontOfQueue(Runnable r)
{
return sendMessageAtFrontOfQueue(getPostMessage(r));
}
send部分
我們發(fā)現(xiàn)蚓庭,send相關(guān)的方法也有5個(gè)模捂,這5個(gè)方法調(diào)用的就是這么幾個(gè)方法
sendMessageDelayed
sendMessageAtTime
sendEmptyMessageDelayed (sendEmptyMessage方法一家獨(dú)占)
public final boolean sendMessage(Message msg)
{
return sendMessageDelayed(msg, 0);
}
public final boolean sendEmptyMessage(int what)
{
return sendEmptyMessageDelayed(what, 0);
}
public final boolean sendEmptyMessageDelayed(int what, long delayMillis) {
Message msg = Message.obtain();
msg.what = what;
return sendMessageDelayed(msg, delayMillis);
}
public final boolean sendEmptyMessageAtTime(int what, long uptimeMillis) {
Message msg = Message.obtain();
msg.what = what;
return sendMessageAtTime(msg, uptimeMillis);
}
public final boolean sendMessageDelayed(Message msg, long delayMillis)
{
if (delayMillis < 0) {
delayMillis = 0;
}
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
殊途同歸,最后10 個(gè)方法都進(jìn)入了enqueueMessage方法
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
我們看到,5個(gè)post方法谐算,5個(gè)send方法银舱,這10個(gè)方法加起來(lái)調(diào)來(lái)調(diào)去也就是另外的4個(gè)方法,分別是
sendMessageDelayed (post和send都有調(diào)用)
sendMessageAtTime (post和send都有調(diào)用)
sendMessageAtFrontOfQueue (postAtFrontOfQueue方法一家獨(dú)有)
sendEmptyMessageDelayed (sendEmptyMessage方法一家獨(dú)占)
我們發(fā)現(xiàn),sendMessageAtTime和sendMessageAtFrontOfQueue這兩個(gè)方法最終都是調(diào)用Handler里面的enqueueMessage方法
sendMessageDelayed調(diào)用了sendMessageAtTime因苹,sendMessageAtTime最后也是調(diào)用enqueueMessage
最曲折的路線,sendEmptyMessageDelayed調(diào)用了sendMessageDelayed篇恒,然后sendMessageDelayed sendMessageAtTime扶檐,最后sendMessageAtTime調(diào)用enqueueMessage。
也就是說(shuō)胁艰,除了post方式的postAtFrontOfQueue方法所調(diào)用的sendMessageAtFrontOfQueue方法不用postAtTime款筑,
其他的post和send加起來(lái)的9個(gè)方法都直接或者間接地調(diào)用了
postAtTime 方法。
小結(jié)
最終腾么,5個(gè)send的方法和5和post的方法奈梳,post和send加起來(lái)的9個(gè)方法都利用postAtTime進(jìn)入了enqueueMessage方法,
剩下1個(gè)的獨(dú)特的postAtFrontOfQueue方法利用sendMessageAtFrontOfQueue也進(jìn)入了enqueueMessage方法
Handler的enqueueMessage方法調(diào)用了MessageQueue里面的enqueueMessage解虱,enqueueMessage就是讓Hadler通過(guò)post或者send發(fā)送過(guò)來(lái)的Message進(jìn)入到MessageQueue的隊(duì)列攘须。
4.3、Handler消息接收的形式
再一遍簡(jiǎn)要地附上handler工作形式
1殴泰、Handler發(fā)送消息僅僅是調(diào)用MessageQueue的enqueueMessage向插入一條信息到MessageQueue
2于宙、Looper不斷輪詢調(diào)用MeaasgaQueue的next方法
3、如果發(fā)現(xiàn)message就調(diào)用handler的dispatchMessage悍汛,ldispatchMessage被成功調(diào)用捞魁,接著調(diào)用handlerMessage()
在4.2里面我們看了Handler的發(fā)送相關(guān)代碼,接下來(lái)看一下接收的员凝。
dispatchMessage方法
dispatchMessage會(huì)判斷三種情況
1署驻、如果是post發(fā)送來(lái)的message奋献,那么就讓這個(gè)message所持有的Runnable執(zhí)行run方法健霹,非常簡(jiǎn)單。
Message的Callback 是一個(gè)Runnable對(duì)象瓶蚂,Handler的post的重載的函數(shù)不管參數(shù)多少糖埋,肯定都是有Runnable的。
private static void handleCallback(Message message) {
message.callback.run();
}
2窃这、如果是利用Handler(Callback callback) 構(gòu)造函數(shù)實(shí)例化的Handler瞳别,也就是構(gòu)造函數(shù)里面?zhèn)魅肓艘粋€(gè)CallBack的對(duì)象,那么就執(zhí)行這個(gè)Callback的handlerMessage杭攻。
利用這個(gè)接口和Handler的一個(gè)構(gòu)造函數(shù)祟敛,我們可以這么創(chuàng)建Handler handler=new Handler(callback)來(lái)創(chuàng)建Handler;備注寫明了這個(gè)接口的作用:可以創(chuàng)建一個(gè)Handler的實(shí)例但是不需要派生Handler的子類。對(duì)比我們?nèi)粘V凶罱?jīng)常做的兆解,就是派生一個(gè)Handler的子類馆铁,復(fù)寫handleMessage方法,而通過(guò)上面的代碼锅睛,我們有了一種新的創(chuàng)建Handler方式埠巨,那就是不派生子類历谍,而是通過(guò)Callback來(lái)實(shí)現(xiàn)。
這種方式非常少用辣垒。
看一下Handler里面的Callback這個(gè)接口的設(shè)計(jì)
public interface Callback {
public boolean handleMessage(Message msg);
}
3望侈、如果是send方法發(fā)送的,那么就執(zhí)行handleMessage勋桶,這個(gè)方法我們非常熟悉了脱衙,google的給的備注的也說(shuō)了,子類必須實(shí)現(xiàn)方法以接受這些Message例驹。這也就是我們最常見(jiàn)的最常用的方式了岂丘。
/**
* Subclasses must implement this to receive messages.
*/
public void handleMessage(Message msg) {
}