一、什麼是handler
Handler 是可以 傳送 和 處理 Meaaage和關聯Thread的MessageQueue的Runable物件。每個handler例項都關聯著一個單獨的執行緒 和這個Thread 的MessageQueue.
Handler將Message 和Runable傳遞到訊息佇列中,並將它們從訊息佇列中取出來進行處理
二、handler有什麼用
- 1、傳送、處理訊息
安排Message和Runable未來的時間點執行。 - 2、執行緒切換
排隊(enqueue)執行不同於自己執行緒的行動(action)
三、handler怎麼使用
方式1、通過handler.sendMessage()
//定義一個Handler 靜態內部類
public static class MyHandler extends Handler{
//弱引用activity
private WeakReference<HandlerActivity> mActivity;
public MyHandler(HandlerActivity handlerActivity) {
super();
//弱引用activity
mActivity =new WeakReference<HandlerActivity>(handlerActivity);
}
//handleMessage 執行在主執行緒 接收訊息
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
HandlerActivity activity = mActivity.get();
switch (msg.what){
case 1:
Log.e("wd_handler","receive message!");
Long threadId = Thread.currentThread().getId();
Log.e("wd_handler","receive message! threadId-->"+threadId);
activity.mPost.setText("receive");
default:
}
}
}
// 2、傳送訊息
public void send(){
Message message = mMyHandler.obtainMessage(1);
Bundle bundle = new Bundle();
bundle.putString("name","xiaomi");
message.setData(bundle);
Log.e("wd_handler","send message!");
mMyHandler.sendMessage(message);
}
// 3、也可以在 子執行緒中傳送訊息
public void sendInThread(){
//建立執行緒
new Thread(new Runnable() {
@Override
public void run() {
Message message = mMyHandler.obtainMessage(1);
Bundle bundle = new Bundle();
bundle.putString("name","xiaomi");
message.setData(bundle);
Log.e("wd_handler","send message in thread!");
Long threadId = Thread.currentThread().getId();
Log.e("wd_handler","get message! threadId-->"+threadId);
//在子執行緒中 傳送訊息
mMyHandler.sendMessage(message);
}
}).start();
}
複製程式碼
方式2、通過handler.post(Runnable)
public void post(){
//建立一個執行緒
new Thread(new Runnable() {
@Override
public void run() {
//子執行緒
Long threadId = Thread.currentThread().getId();
Log.e("wd_handler","post message! threadId-->"+threadId);
//子執行緒中 post訊息 至主執行緒
mMyHandler.post(new Runnable() {
@Override
public void run() {
//主執行緒
Long threadId = Thread.currentThread().getId();
Log.e("wd_handler","get message! threadId-->"+threadId);
mPost.setText("呵呵");
}
});
}
}).start();//開啟執行緒
}
複製程式碼
四、handler內部原理機制
從Handler的定義和使用中發現handler,有兩個作用:
- 傳送和處理訊息
- 進行執行緒的排程
1)如何傳送訊息
1、無論是sendMessage() 還是post(Runable)方法都是呼叫sendMessageDelayed(Message msg,long delayMillis)
//post(Runnable)
public final boolean post(Runnable r)
{
return sendMessageDelayed(getPostMessage(r), 0);
}
//sendMessage(Message msg)
public final boolean sendMessage(Message msg)
{
return sendMessageDelayed(msg, 0);
}
複製程式碼
2、sendMessageDelayed
public final boolean sendMessageDelayed(Message msg, long delayMillis)
{
if (delayMillis < 0) {
delayMillis = 0;
}
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
複製程式碼
3、sendMessageAtTime
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);
}
複製程式碼
4、enqueueMessage()
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
複製程式碼
msg.target = this;這句程式碼 是將message 和 Handler繫結 ,然後在通過MessageQueue.enqueueMessage()將Message 傳送到訊息佇列中。
5、MessageQueue.enqueueMessage()
boolean enqueueMessage(Message msg, long when) {
....
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;
}
...
return true;
}
複製程式碼
2)如何取出訊息
1、訊息傳送到MessageQueue 中 然後通過Looper.loop()方法取出。
public static void loop() {
//1、通過ThreadLocal 獲得當前執行緒的 looper
final Looper me = myLooper();
if (me == null) {
throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
}
//2、通過Looper 獲得當前Looper 對應的訊息佇列
final MessageQueue queue = me.mQueue;
//3、for死迴圈,通過MessageQuene.next() 獲得該訊息佇列中的Message
for (;;) {
Message msg = queue.next(); // might block
if (msg == null) {
// No message indicates that the message queue is quitting.
return;
}
//4、通過Message中繫結的target 獲得Handler;然後呼叫dispatchMessage()方法。
try {
msg.target.dispatchMessage(msg);
end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
//5、回收訊息
msg.recycleUnchecked();
}
}
複製程式碼
6、handler的dispatchMessage() 方法回撥 到handleCallback方法中
/**
* 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);
}
}
複製程式碼
3)如何進行執行緒排程
以上的方法主要分析的是Message如何傳送出去以及如何的分發處理,並未涉及的執行緒相關的分析。那麼handler如何進行執行緒的切換呢?
//1、建立Handler時,獲取當前執行緒的Looper(),例如 執行緒1
Handler handler = new Handler();
public Handler(Callback callback, boolean async) {
//通過 sThreadLocal 獲得looper
mLooper = Looper.myLooper();
//判斷當前執行緒是否配呼叫過Looper.prepare()
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread that has not called Looper.prepare()");
}
// 獲得looper對應的佇列
mQueue = mLooper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
//2、線上程2 中通過handler傳送訊息
public void sendInThread(){
new Thread(new Runnable() {
@Override
public void run() {
Message message = mMyHandler.obtainMessage(1);
Bundle bundle = new Bundle();
bundle.putString("name","xiaomi");
message.setData(bundle);
Log.e("wd_handler","send message in thread!");
Long threadId = Thread.currentThread().getId();
Log.e("wd_handler","get message! threadId-->"+threadId);
mMyHandler.sendMessage(message);
}
}).start();
}
複製程式碼
- 3、通過之前對Message傳送過程的分析得知,
handler 傳送訊息(執行緒2操作)至 建立Handler執行緒(執行緒1)的MessageQueue 中,(因為handler建立的時候就初始化繫結了建立執行緒的looper) 然後在經過(執行緒1)Looper ,輪詢message.
最後 handler再呼叫HandlerMessage方法。
- 4、執行緒切換總結:
傳送訊息的 執行緒1 通過Handler傳送訊息到 建立handler的 執行緒2!!!(必須呼叫Looper.prepare()方法!)