盒子
盒子

Handle消息机制

Handler的基本使用

子线程到主线程

1
2
3
4
5
6
7
8
9
10
//主线程
private handler=new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
}
};

//子线程
handler.sendEmptyMessage();

主线程到子线程

1
2
3
4
5
6
7
8
9
10
11
12
//主线程
Looper.prepare();
handler.sendEmptyMessage();
Looper.loop();

//子线程
private handler=new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
}
};

Handler作为Message的发送类,也作为Message的处理类

Message作为消息供Handler发送:

1
2
3
4
handler.obtainMessage(MESSAGE,handler).sendToTarget();

Message message=Message.obtain();
handler.sendMessage(message)

obtainMessage会从公共循环池里获取消息,比创建新实例效率更高

获取Message内容:

1
2
3
4
5
6
7
8
9
10
11
new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch(msg.what){
case 1:
Object obj=msg.Obj;
break;
}
}
};

常通过Handler与Looper进行交互,Handler为指定Looper提供了发送消息和处理消息的方法

通常创建Handler需要指定一个Looper与其绑定,如:

1
2
3
Looper.prepare()
handler.sendEmptyMessage();
Looper.loop();

Looper.prepare()

启动一个Looper

Looper.loop()

让Looper开始工作,在调用该方法后,会阻塞线程,导致该方法后面的代码无法执行,直到调用handler.getLooper().quit() 才能解除阻塞

但在主线程中创建Handler会默认与主线程中的Looper绑定,即:

handler = new Handler()等价于new Handler(Looper.myLooper())

Looper.myLooper()

获取当前进程的Looper

HandleThread的基本使用

用于启动具有looper的新线程的类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class LoaderThread <T> extends HandlerThread {
public LoaderThread() {
super(TAG);
}
@Override
protected void onLooperPrepared() {
super.onLooperPrepared();
Log.i(TAG,"onLooperPrepared");
}
}
}
//通过以下方式启动线程,启动后会执行onLooperPrepared方法
LoaderThread<InnerHolder> loaderThread=new LoaderThread<>();
loaderThread.start();
loaderThread.getLooper();

关系图

关系图

Looper对象的内部又维护有唯一的一个MessageQueue,所以一个线程可以有多个handler,
但是只能有一个Looper和一个MessageQueue

源码分析

建立完整的消息机制Looper,MessageQuery,Handler一个都不能少,Handler用于发送和接收消息,MessageQuery用于存放消息,Looper用于从MessageQuery中不停的取消息

在Looper向MessageQuery取消息时需要调用prepare方法:

Looper.java:

1
2
3
4
5
6
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));
}

该方法将一个本线程下创建的一个Looper添加到ThreadLocal中

创建Handler对象重写Callback的handleMessage方法:

Handler.java:

1
2
3
4
5
6
7
8
9
10
11
public Handler(Callback callback) {
this(callback, false);
}

public interface Callback {
/**
* @param msg A {@link android.os.Message Message} object
* @return True if no further handling is desired
*/
public boolean handleMessage(Message msg);
}

最后启动looper让其不断向MessageQuery取出对象,以下为loop方法中的部分代码:

Looper.loop:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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);
dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
.....

可见其无限循环地向MessageQuery取消息:

MessageQuery.java:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
Message next() {
.....
synchronized (this) {
final long now = SystemClock.uptimeMillis();
Message prevMsg = null;
Message msg = mMessages;
if (msg != null && msg.target == null)
do {
prevMsg = msg;
msg = msg.next;
} while (msg != null && !msg.isAsynchronous());
}
if (msg != null) {
if (now < msg.when) {
nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
} else {
mBlocked = false;
if (prevMsg != null) {
prevMsg.next = msg.next;
} else {
mMessages = msg.next;
}
msg.next = null;
if (DEBUG) Log.v(TAG, "Returning message: " + msg);
msg.markInUse();
return msg;
}
} else {
nextPollTimeoutMillis = -1;
}
}
}
......
}

由上代码可知Message是一个链表结构地对象,通过一系列判断最终找到looper需要取出的消息,并返回

在拿到Message后会调用:

1
msg.target.dispatchMessage(msg);

即发送该消息的handler的dispatchMessage方法:

Handler.java:

1
2
3
4
5
6
7
8
9
10
11
12
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}

其中mCallback便是之前我们重写了的Callback接口

再来跟踪Handler发送消息的过程:

Handler.java:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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);
}

private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}

最终来到了MessageQuery类中的enqueueMessage方法:

MessageQuery.java:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
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) {
//使用发送过来的消息
msg.next = p;
mMessages = msg;
needWake = mBlocked;
} else {
//不使用发送过来的消息,通过链表查询其它消息作为第一条消息
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;
prev.next = msg;
}

if (needWake) {
nativeWake(mPtr);
}
}
return true;
}

以上代码可以看出handler向MessageQuery发送消息后最终会调用enqueueMessage方法确定是否将该消息作为消息队列的第一条消息

至于另一种使用方式:post,可追踪其代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public final boolean post(Runnable r)
{
return sendMessageDelayed(getPostMessage(r), 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);
}

经过以上方法最终一样来当了enqueueMessage,所以可重点分析getPostMessage(r):

Handler.java:

1
2
3
4
5
private static Message getPostMessage(Runnable r) {
Message m = Message.obtain();
m.callback = r;
return m;
}

再回到将消息转交给handler进行处理的地方:

Handler.java:

1
2
3
4
5
6
7
8
9
10
11
12
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}

msg.callback是什么便一目了然了:即

1
2
3
4
5
6
handler.post(new Runnable() {
@Override
public void run() {

}
});

关系图

支持一下
扫一扫,支持Grooter
  • 微信扫一扫
  • 支付宝扫一扫