HandlerThread、IntentService 理解

HandlerThread

HandlerThread 继承 Thread,HandlerThread 本质上就是一个普通 Thread,只不过内部建立了 Looper,因此拥有自己的消息队列。不适合频繁处理耗时操作,因为消息是串行处理的,某个人任务执行时间过长,会导致后续的任务被延迟处理

通过调用 Thread 的 start 方法开始运行
结束消息轮询也是通过操作 Looper 实现的,退出 Looper 后,线程没有可执行代码,则会自动结束

源码

在 run 方法内初始化

1
2
3
4
5
6
7
8
Looper.prepare();
synchronized (this) {
mLooper = Looper.myLooper();
notifyAll();
}
Process.setThreadPriority(mPriority);
onLooperPrepared();
Looper.loop(); //开启轮询,因此除非主动退出,否则线程不会结束

1
2
3
4
5
6
7
8
public boolean quit() {
Looper looper = getLooper();
if (looper != null) {
looper.quit();
return true;
}
return false;
}

还有个 quitSafely 方法。二者的区别是调用了 MessageQueue 的 void quit(boolean safe) 方法

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
// MessageQueue
void quit(boolean safe) {
···
if (safe) {
removeAllFutureMessagesLocked();
} else {
removeAllMessagesLocked();
}
···
}

// removeAllMessagesLocked 方法,将队列里的所有消息不经检查直接回收
private void removeAllMessagesLocked() {
Message p = mMessages;
while (p != null) {
Message n = p.next;
p.recycleUnchecked();
p = n;
}
mMessages = null;
}

//removeAllFutureMessagesLocked 会将延时消息移除,非延迟消息会派发
private void removeAllFutureMessagesLocked() {
final long now = SystemClock.uptimeMillis();
Message p = mMessages;
if (p != null) {
if (p.when > now) {
removeAllMessagesLocked();
} else {
Message n;
for (;;) {
n = p.next;
if (n == null) {
return;
}
if (n.when > now) {
break;
}
p = n;
}
p.next = null;
do {
p = n;
n = p.next;
p.recycleUnchecked();
} while (n != null);
}
}
}

IntentService

四大组件是在主线程的,不可执行耗时操作。
IntentService 是个抽象类,需要实现抽象方法 onHandleIntent(可在该方法内执行耗时操作)。IntentService 会拥有消息队列(内部使用了 HandlerThread 的 Looper),且会在回调 onHandleIntent 后自动 stopSelf,销毁 Service。

源码

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
@Override
public void onCreate() {
super.onCreate();
HandlerThread thread = new HandlerThread("IntentService[" + mName + "]"); //创建 HandlerThread 实例,并开启线程(Looper 轮询)
thread.start();

mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);
}

// ServiceHandler 收到消息后回调 onHandleIntent,执行用户的操作,执行完后销毁自身
private final class ServiceHandler extends Handler {
public ServiceHandler(Looper looper) {
super(looper);
}

@Override
public void handleMessage(Message msg) {
onHandleIntent((Intent)msg.obj);
stopSelf(msg.arg1);
}
}

// 开启 Service 后就发送个消息
@Override
public void onStart(@Nullable Intent intent, int startId) {
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
msg.obj = intent;
mServiceHandler.sendMessage(msg);
}