Android中Handler機(jī)制介紹以及分析分為下面幾個(gè)部分闡述
- Handler的介紹和作用
- Handler的使用場(chǎng)景示例
- Handler機(jī)制源碼分析
- HandlerThread使用和分析
- Handler總結(jié)
- 一些疑問和異常
ok,現(xiàn)在進(jìn)入正題
一,Handler的介紹和作用
關(guān)于Handler的介紹我們首先從安卓官網(wǎng)查閱

上面大致的意思如下:
Handler可以發(fā)送和處理Message和Runnable對(duì)象到關(guān)聯(lián)的線程的MessageQueue.每一個(gè)Handler實(shí)例關(guān)聯(lián)到一個(gè)唯一的線程和這個(gè)線程的MessageQueue.當(dāng)我們創(chuàng)建一個(gè)新的Handler時(shí)他將綁定創(chuàng)建它的線程以及這個(gè)線程的消息隊(duì)列.
-
Handler兩個(gè)主要的用途
- 安排Message和Runnable在合適的時(shí)間被執(zhí)行
- 入隊(duì)一個(gè)Action在其他線程中執(zhí)行.
-
send Message和post Runnable的方法
- post版本
post(Runnable),
postAtTime(Runnable, long),
postDelayed(Runnable,long)
對(duì)于Post版本的方法,將Runnable對(duì)象入隊(duì)到MessageQueue被調(diào)用,最終是Message中執(zhí)行 - send版本
sendEmptyMessage(int),
sendMessage(Message),
sendMessageAtTime(Message,long), sendMessageDelayed(Message,long)
對(duì)于Send版本的方法,將Message對(duì)象入隊(duì)后,然后被Handler的handleMessage(Message)方法處理
- post版本
當(dāng)應(yīng)用(App)的進(jìn)程被創(chuàng)建后, 主線程默認(rèn)的就會(huì)創(chuàng)建并運(yùn)行一個(gè)與之相關(guān)聯(lián)的消息隊(duì)列,用來管理頂級(jí)的應(yīng)用對(duì)象(activities, broadcast receivers等)以及窗口的創(chuàng)建.
可以在創(chuàng)建的線程中創(chuàng)建新的消息隊(duì)列,通過Handler可以和主線程進(jìn)行交互,使用到上面的Post版本和Send版本的方法
二,Handler使用示例
1,子線程和主線程交互
對(duì)于子線程和主線程通過Handler交互, 可以是子線程向主線程發(fā)送消息(例如,更新UI),也可以主線程向子線程發(fā)送消息(例如,完成某個(gè)特定的操作)
下面代碼說明
private Handler mMainHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
System.out.println("主線程"+Thread.currentThread().getName()+" Handler 收到消息:"+msg.obj);
Message message = Message.obtain();
message.obj = "消息是從主線程中發(fā)出的";
mSubHandler.sendMessage(message);
}
};
private Handler mSubHandler;
private void test(){
new Thread(){
@Override
public void run() {
super.run();
Looper.prepare();
mSubHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
System.out.println("子線程"+Thread.currentThread().getName()+" Handler 收到消息:"+msg.obj);
Message message = Message.obtain();
message.obj = "消息是從子線程中發(fā)出的";
mMainHandler.sendMessage(message);
//子線程Looper不在使用時(shí)退出,主線程的不能退出,否則throw new IllegalStateException("Main thread not allowed to quit.");
mSubHandler.getLooper().quitSafely();
}
};
Looper.loop();
}
}.start();
Message msg = new Message();
msg.obj = "開始發(fā)送消息";
mMainHandler.sendMessage(msg);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
test();
}
2,子線程Post一個(gè)Action
對(duì)于Post版本的方法,最終處理是在MessageQueue中的Message,所以handleMessage接收不到
private Handler mMainHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
//對(duì)于Post版本的方法,最終處理是在MessageQueue中的Message,所以在這里是接收不到的
}
};
private void test(){
new Thread(){
@Override
public void run() {
super.run();
mMainHandler.post(new Runnable() {
@Override
public void run() {
System.out.println("Post一個(gè)Action");
}
});
}
}.start();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
test();
}
三,Handler機(jī)制源碼分析
Handler機(jī)制與之相關(guān)的類 ,有Handler,Looper,Message, MessageQueue
下面的分析以我們使用一個(gè)Handler發(fā)送一個(gè)消息或者Action的方法調(diào)用順序開始
當(dāng)我們?cè)谝粋€(gè)線程中創(chuàng)建Handler且關(guān)聯(lián)Looper消息隊(duì)列需要
Looper中的prepare()方法用來初始化當(dāng)前線程Looper,然后創(chuàng)建Handler關(guān)聯(lián)他,然后調(diào)用Looper的loop()方法
Looper.prepare();
Handler subHandler = new Handler();
Looper.loop();
1,Looper中的prepare()方法
public static void prepare() {
prepare(true);
}
2,調(diào)用重載的prepare(boolean)方法
這個(gè)方法new一個(gè)Looper然后與當(dāng)前線程關(guān)聯(lián),然后將其存放到ThreadLocal中
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));
}
3, 然后看下Looper對(duì)象在創(chuàng)建的時(shí)候都做了什么
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
很簡(jiǎn)單,Looper在創(chuàng)建時(shí)創(chuàng)建一個(gè)消息隊(duì)列,也就是Looper與之唯一對(duì)應(yīng)
4,Handler發(fā)送消息或者post Runnable
- 發(fā)送消息
public final boolean sendMessage(Message msg)
{
return sendMessageDelayed(msg, 0);
}
public final boolean sendMessageDelayed(Message msg, long delayMillis)
{
if (delayMillis < 0) {
delayMillis = 0;
}
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
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);
}
- post Runnable
public final boolean post(Runnable r)
{
return sendMessageDelayed(getPostMessage(r), 0);
}
private static Message getPostMessage(Runnable r) {
Message m = Message.obtain();
m.callback = r;
return m;
}
public final boolean sendMessageDelayed(Message msg, long delayMillis)
{
if (delayMillis < 0) {
delayMillis = 0;
}
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
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);
}
不管是發(fā)送消息還是Post Runnable最終都是調(diào)用sendMessageAtTime(Message msg, long uptimeMillis)
然后enqueueMessage(queue, msg, uptimeMillis)入到消息隊(duì)列中
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
上面的這個(gè)函數(shù)函數(shù)有很重要的一行msg.target = this, 將當(dāng)前發(fā)送Message的Handler賦值給這個(gè)msg的target, 這個(gè)target將來在Looper中取得消息后進(jìn)行分發(fā)的Handler對(duì)象.
接下來就是調(diào)用MessageQueue的消息入隊(duì)
5,MessageQueue的入隊(duì)操作
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;
//如果消息隊(duì)列為空,那么改Message就作為頭結(jié)點(diǎn)
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;
//尋找合適的插入位置,是按照消息的將要被處理的先后順序來處理的(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;
}
// We can assume mPtr != 0 because mQuitting is false.
if (needWake) {
nativeWake(mPtr);
}
}
return true;
}
MessageQueue插入的Message時(shí)候
1)首先會(huì)有各種判斷, 消息的target(也就是發(fā)送和將來處理消息的Handler)是否為空, Message是否在使用, 消息隊(duì)列是否退出等前提條件
2)插入Message到消息隊(duì)列的合適位置
如果消息隊(duì)列為空,那么該Message就作為頭結(jié)點(diǎn)
否則就根據(jù)消息將要執(zhí)行的先后順序(when)來進(jìn)行比較找到插入的位置
6,Looper.loop()
Looper中的loop負(fù)責(zé)來取出消息隊(duì)列中的Message,如果消息隊(duì)列為空,則阻塞,如果調(diào)用quit或者quitSafely方法退出消息機(jī)制,那么取出的msg為空,將退出. 否則執(zhí)行消息的派發(fā)
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;
}
... ...
try {
msg.target.dispatchMessage(msg);
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
... ....
msg.recycleUnchecked();
}
}
msg.target.dispatchMessage(msg)中的target就是發(fā)送Message到MessageQueue的Handler,所以發(fā)送Message到MessageQueue的Handler和Looper從MessageQueue取出Message進(jìn)行派發(fā)處理的也是這個(gè)Handler
7,Handler的dispatchMessage
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
這個(gè)就是Message最終處理的地方,轉(zhuǎn)了一大圈又回到了原點(diǎn)
首先分兩部分說明他是怎么派發(fā)的
- if (msg.callback != null)
這個(gè)對(duì)應(yīng)的是handler post Runnable對(duì)象情況
private static void handleCallback(Message message) {
message.callback.run();
}
這個(gè)時(shí)候直接執(zhí)行Runnable對(duì)象的run()方法,不會(huì)被Handler的handleMessage方法處理
- msg.callback == null
這個(gè)對(duì)應(yīng)的是handler 發(fā)送消息(sendMessage)的情形
也就是上面的else代碼分之
首先他會(huì)判斷handler對(duì)象中的mCallback是否為空,這個(gè)對(duì)象類型如下:
public interface Callback {
public boolean handleMessage(Message msg);
}
這個(gè)接口在構(gòu)造Handler對(duì)象的時(shí)候使用
public Handler(Looper looper, Callback callback, boolean async) {
mLooper = looper;
mQueue = looper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
如果在創(chuàng)建Handler實(shí)例時(shí),傳入了Callback接口,如果handleMessage(Message)方法返回true,則截?cái)噙@個(gè)Message向下傳遞,直接返回.
如果Callback不為空且返回false或者Callback為空,那么就由我們創(chuàng)建Handler覆寫的handleMessage(Message)處理,這個(gè)方法是不是很熟悉呢?
到此,消息機(jī)制的創(chuàng)建,以及處理流程完畢,下面用一個(gè)圖

四,HandlerThread使用和分析
HandlerThread提供了一個(gè)便于建立子線程消息機(jī)制的一種方式.
使用如下:
HandlerThread ht = new HandlerThread("sub");
ht.start();
Handler handler = new Handler(ht.getLooper());
他很簡(jiǎn)單的就創(chuàng)建一個(gè)子線程,以及這個(gè)線程對(duì)應(yīng)的Looper,MessageQueue,然后將一個(gè)Handler關(guān)聯(lián)到這個(gè)線程和消息隊(duì)列
HandleThread代碼不多,他的實(shí)現(xiàn)精髓就是run()方法和getLooper()方法
public void run() {
mTid = Process.myTid();
Looper.prepare();
synchronized (this) {
mLooper = Looper.myLooper();
notifyAll();
}
Process.setThreadPriority(mPriority);
onLooperPrepared();
Looper.loop();
mTid = -1;
}
public Looper getLooper() {
if (!isAlive()) {
return null;
}
// If the thread has been started, wait until the looper has been created.
synchronized (this) {
while (isAlive() && mLooper == null) {
try {
wait();
} catch (InterruptedException e) {
}
}
}
return mLooper;
}
當(dāng)線程啟動(dòng),就開始執(zhí)行run方法 他首先就開始創(chuàng)建一個(gè)Looper,然后給變量mLooper賦值,然后notifyAll由于獲得Looper被阻塞的線程
getLooper()方法返回Looper對(duì)象,然后關(guān)聯(lián)到Handler對(duì)象,建立消息機(jī)制.但是由于線程異步,所以可能在獲取的時(shí)候,Looper對(duì)象還沒有創(chuàng)建出來,所以有一個(gè)wait()操作
五,Handler總結(jié)
- 每個(gè)線程都對(duì)應(yīng)唯一的一個(gè)Looper和唯一的一個(gè)MessageQueue
- 每個(gè)Looper可以對(duì)應(yīng)多個(gè)Handler
- 每個(gè)Handler對(duì)應(yīng)唯一的一個(gè)Looper和MessageQueue
- 那個(gè)Handler 發(fā)送消息,最終經(jīng)過hanler->messagequeue->loop->handler回到原點(diǎn)由那個(gè)Handler處理
- 當(dāng)我們要在子線程中建立消息機(jī)制時(shí),推薦使用HandlerThread
- 當(dāng)我們?cè)谧泳€程中簡(jiǎn)歷消息機(jī)制時(shí),如果不再使用,要調(diào)用quit()或者quitSafely()退出
最后,在舉一個(gè)??來說明這個(gè)Handler機(jī)制
假設(shè)你所在的公司只有一個(gè)領(lǐng)導(dǎo)(Looper), 只有一個(gè)OA系統(tǒng)(MessageQueue),多個(gè)員工(Handler).
當(dāng)你(Handler)有女票千里奔襲機(jī)動(dòng)千里,突然奔襲而來,你(Handler)向OA(MessageQueue)提交請(qǐng)假事由(Message),你的領(lǐng)導(dǎo)(Looper)看到這個(gè)不可拒絕的理由(Message),將這個(gè)事由派發(fā)給你(Handler),然后你(Hanlder)處理---接駕
六,一些疑問和異常
1,為什么我們平時(shí)使用Handler時(shí)候沒有寫過Looper.prepare()h和Looper.loop()方法呢?
因?yàn)槲覀兤綍r(shí)使用的Handler都是在主線程中創(chuàng)建的, 當(dāng)應(yīng)用啟動(dòng),ActivityThread類中已經(jīng)初始化了
public static void main(String[] args) {
... ...
Looper.prepareMainLooper();
ActivityThread thread = new ActivityThread();
thread.attach(false);
if (sMainThreadHandler == null) {
sMainThreadHandler = thread.getHandler();
}
... ...
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
2,throw new RuntimeException( "Can't create handler inside thread that has not called Looper.prepare()");
由于在子線程中創(chuàng)建Handler時(shí)候沒有初始化對(duì)應(yīng)的Looper(每個(gè)Handler要對(duì)應(yīng)一個(gè)Looper的)
3, throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
由于在子線程中創(chuàng)建Handler時(shí)候,調(diào)用Looper.loop()之前一定要調(diào)用Looper.prepare()