目录
前言
众所周知如果想要在Android中执行耗时操作需要新建一个线程然后在该线程中实现,但是如果出现一种需要我们频繁进行耗时操作的业务,那我们再频繁的创建线程无疑会使性能降低,而Android SDK为我们提供了一个循环线程的框架刚好可以帮助我们解决这个问题,它就是HandlerThread。
原理
HandlerThread继承了Thread,集成了Looper和MessageQueue,在内部实现了一个消息队列,队列中的消息是顺序执行的因此线程是安全的,HandlerThread内部机制确保了在创建Looper和发送消息之间不存在竞态条件,这个是通过HandlerThread.getLooper()实现为一个阻塞操作实现的,只有当HandlerThread准备好接收消息消息之后才会返回。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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84public class HandlerThread extends Thread {
int mPriority;
int mTid = -1;
Looper mLooper;
public HandlerThread(String name) {
super(name);
mPriority = Process.THREAD_PRIORITY_DEFAULT;
}
/**
* Constructs a HandlerThread.
* @param name
* @param priority The priority to run the thread at. The value supplied must be from
* {@link android.os.Process} and not from java.lang.Thread.
*/
public HandlerThread(String name, int priority) {
super(name);
mPriority = priority;
}
/**
* Call back method that can be explicitly overridden if needed to execute some
* setup before Looper loops.
*/
protected void onLooperPrepared() {
}
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;
}
// 如果线程已经启动那么在Looper准备好之前应该等待
synchronized (this) {
while (isAlive() && mLooper == null) {
try {
wait();
} catch (InterruptedException e) {
}
}
}
return mLooper;
}
public boolean quit() {
Looper looper = getLooper();
if (looper != null) {
looper.quit();
return true;
}
return false;
}
public boolean quitSafely() {
Looper looper = getLooper();
if (looper != null) {
looper.quitSafely();
return true;
}
return false;
}
/**
* Returns the identifier of this thread. See Process.myTid().
*/
public int getThreadId() {
return mTid;
}
}
实现
对外开放Handler实例
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
31public class MainActivity extends AppCompatActivity {
private HandlerThread mHandlerThread;
private Handler mBgHandler;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initHandler();
}
private void initHandler() {
mHandlerThread=new HandlerThread("myHandlerThread");
mHandlerThread.start();
mBgHandler=new Handler(mHandlerThread.getLooper(), new Handler.Callback() {
public boolean handleMessage(Message message) {
switch (message.what){
case 0:
// 执行操作
break;
}
return false;
}
});
}
protected void onDestroy() {
super.onDestroy();
mHandlerThread.quit();
}
}对外隐藏Handler(需要继承HandlerThread并在onLooperPrepared方法中对Handler进行实例化)
1 | public class MyHandlerThread extends HandlerThread { |
Activity中调用
1 | public class MainActivity extends AppCompatActivity { |