HandlerThread

了解HandlerThread这一篇就够了

本文我们讲解的是HandlerThread,可能有部分同学不了解或者没用过这个类。原因很简单,在如今大神们的框架面前,许多的原生类已经不为人所用了,然而早期开发者要想在子线程里更新UI则需要在Thread里创建一个Handler。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class MyThread : Thread() {
private lateinit var mHandler: Handler

override fun run() {
super.run()
Looper.prepare()

mHandler = object : Handler() {
override fun handleMessage(msg: Message?) {
super.handleMessage(msg)
if(msg?.what==0){
//...处理消息
}
}
}

Looper.loop()
}
}

是不是认为很难受?每次要想在子线程里面处理信息必须每次在子线程里创建Handler?



然而贴心的Google工程师为我们提供了一个自带Handler的类,名叫
HandlerThread



类注释

要想学习一个类的构成,首先要从它的类注释看起。

1
2
3
4
5
6
7
**
* Handy class for starting a new thread that has a looper. The looper can then be
* used to create handler classes. Note that start() must still be called.
*/
public class HandlerThread extends Thread {
...
}
  • 由它的注释可以看出,这是一个带有LooperThread,这个Looper可以被用于创建Handler,请注意,start()这个方法仍然需要被调用。
  • 总结一下,这个类就是自带Handler的线程类。

构造方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
int mPriority;//优先级
int mTid = -1;
Looper mLooper;//自带的Looper
private @Nullable Handler mHandler;

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;
}
  • 这里有两个构造方法,一个HandlerThread(String name),一个HandlerThread(String name, int priority),我们可以自己设定线程的名字以及优先级。注意!是Process里的优先级而不是Thread的。
1
2
3
4
5
6
7
8
9
10
11
12
//这是可选的优先级
public static final int THREAD_PRIORITY_DEFAULT = 0;
public static final int THREAD_PRIORITY_LOWEST = 19;
public static final int THREAD_PRIORITY_BACKGROUND = 10;
public static final int THREAD_PRIORITY_FOREGROUND = -2;
public static final int THREAD_PRIORITY_DISPLAY = -4;
public static final int THREAD_PRIORITY_URGENT_DISPLAY = -8;
public static final int THREAD_PRIORITY_VIDEO = -10;
public static final int THREAD_PRIORITY_AUDIO = -16;
public static final int THREAD_PRIORITY_URGENT_AUDIO = -19;
public static final int THREAD_PRIORITY_MORE_FAVORABLE = -1;
public static final int THREAD_PRIORITY_LESS_FAVORABLE = +1;

其他方法

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

/*
在Looper.loop()之前调用的方法,如需要配置可重写
*/
protected void onLooperPrepared() {
}


/*
来自Thread的run方法,调用与start()之后
*/
@Override
public void run() {
mTid = Process.myTid();//线程id
Looper.prepare();//创建子线程的Looper
synchronized (this) {
mLooper = Looper.myLooper();//获取Looper实例
notifyAll();// native方法,用于唤醒所有等待获取Looper的线程
}
Process.setThreadPriority(mPriority);//设置线程优先级
onLooperPrepared();//上面方法的调用
Looper.loop();//Looper开始轮询
mTid = -1;
}

/*
获取Looper
*/
public Looper getLooper() {
//判断线程是否启动
if (!isAlive()) {
return null;
}

synchronized (this) {
while (isAlive() && mLooper == null) {//如果线程启动,且Looper为空
try {
wait();//使其等待直至获取到Looper
} catch (InterruptedException e) {
}
}
}
return mLooper;
}

/*
获取Handler
*/
@NonNull
public Handler getThreadHandler() {
if (mHandler == null) {
mHandler = new Handler(getLooper());
}
return mHandler;
}


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;
}


public int getThreadId() {
return mTid;
}
  • 注释我已写在代码上,在HandlerThread不使用时记得使用 getLooper().quit()来退出这个线程,但需要注意的是quit和quitSafely的区别,接下来我将用较短的篇幅介绍一下这两个方法的区别。

quit()和quitSafely()的区别

HandlerThread:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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;
}

Looper在这两个方法中调用了quit()quitSafely()方法。我们点开源码查看,他们本质都是在调用MessageQueuequit方法,不同的是quit方法的参数不同:

Looper:

quitSafely:

1
2
3
public void quit() {
mQueue.quit(true);
}

quit:

1
2
3
public void quit() {
mQueue.quit(false);
}

如果大家对消息机制有所了解,那么一定知道MessageQueue是用于处理Message(消息)的队列,如果不知道的可以去了解一下。话不多说,接下来我们将深入MessageQueue了解一下quit(boolean safe)方法是何方神圣。

MessageQueue:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
void quit(boolean safe) {
if (!mQuitAllowed) {
throw new IllegalStateException("Main thread not allowed to quit.");
}

synchronized (this) {
if (mQuitting) {
return;
}
mQuitting = true;

if (safe) {//敲黑板!这就是quitSafely和quit的区别
removeAllFutureMessagesLocked();
} else {
removeAllMessagesLocked();
}

// We can assume mPtr != 0 because mQuitting was previously false.
nativeWake(mPtr);
}
}
  • 当我们在Looper中调用quitSafely()时,在MessageQueue里调用的removeAllFutureMessagesLocked()方法
  • 当我们在Looper中调用quit()时,在MessageQueue里调用的是removeAllMessagesLocked()方法
  • 而这两个方法本质的区别就是在于remove消息的范围,下面是一段伪代码:
    1
    2
    3
    4
    5
    if (safe) {
    只清空队列中的延时消息(通过postDelay发送的),非延时消息继续派发,直到完成
    } else {
    移除所有消息,包括延时消息
    }

所以说safe的区别就是是否清除所有消息,这两个方法的实现我们就不深究了,毕竟本文是为了讲解HandlerThread而不是数据结构,若有兴趣的可以去自行研究。

应用

  • IntentService的底层就是利用HandlerThread
  • 举个栗子




    Activity:
    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
    class MainActivity : AppCompatActivity() ,Handler.Callback{


    private lateinit var mUIHandler :Handler
    private lateinit var mDownloadThread: DownloadThread

    override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    init()
    }

    private fun init(){
    mUIHandler = Handler(this)

    val list = mutableListOf<String>()
    list.add("url1")
    list.add("url2")
    list.add("url3")

    mDownloadThread = DownloadThread("Download")
    .setUrls(list)
    .setUIHandler(mUIHandler)

    mDownloadThread.start()
    Log.d("test","开始下载")
    }

    override fun handleMessage(msg: Message?): Boolean {
    when(msg?.what){
    DownloadThread.START->{
    Log.d("test","Activity接收到了START信息")
    }
    DownloadThread.FINISH->{
    Log.d("test","Activity接收到了FINISH信息")
    }
    }
    return true
    }
    }




DownloadThread:

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
class DownloadThread(name: String?) : HandlerThread(name), Handler.Callback {
private lateinit var mWorkHandler: Handler
private lateinit var mUIHandler: Handler
private lateinit var urls: List<String>

companion object {
const val START = 1
const val FINISH = 2
const val KEY = "getUrl"
}

fun setUIHandler(mUIHandler: Handler): DownloadThread {
this.mUIHandler = mUIHandler
return this
}

fun setUrls(urls: List<String>): DownloadThread {
this.urls = urls
return this
}

override fun onLooperPrepared() {
super.onLooperPrepared()
if (looper != null)
mWorkHandler = Handler(looper, this)

//在这里发送下载信息
urls.forEach { url->
val message = mWorkHandler.obtainMessage()
val bundle = Bundle()
bundle.putString(KEY,url)
message.data = bundle
mWorkHandler.sendMessage(message)
}
}


//mWorkHandler的handleMessage
override fun handleMessage(msg: Message?): Boolean {
if (msg == null || msg.data == null) return false

val url = msg.data.get(KEY) as String//获取url

val startMessage: Message = mUIHandler.obtainMessage(START)
mUIHandler.sendMessage(startMessage)
Log.d("test","$url :Thread发送START信息")

Thread.sleep(2000)
Log.d("test","$url :Thread执行耗时操作中...")

val finishMessage: Message = mUIHandler.obtainMessage(FINISH)
mUIHandler.sendMessage(finishMessage)
Log.d("test","$url :Thread发送FINISH信息")
return true
}
}

结果:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2019-01-30 20:47:47.743  D/test: 开始下载

2019-01-30 20:47:47.744 D/test: url1 :Thread发送START信息
2019-01-30 20:47:47.776 D/test: Activity接收到了START信息
2019-01-30 20:47:49.746 D/test: url1 :Thread执行耗时操作中...
2019-01-30 20:47:49.747 D/test: url1 :Thread发送FINISH信息
2019-01-30 20:47:49.747 D/test: Activity接收到了FINISH信息

2019-01-30 20:47:49.747 D/test: url2 :Thread发送START信息
2019-01-30 20:47:49.747 D/test: Activity接收到了START信息
2019-01-30 20:47:51.748 D/test: url2 :Thread执行耗时操作中...
2019-01-30 20:47:51.749 D/test: url2 :Thread发送FINISH信息
2019-01-30 20:47:51.750 D/test: Activity接收到了FINISH信息

2019-01-30 20:47:51.749 D/test: url3 :Thread发送START信息
2019-01-30 20:47:51.750 D/test: Activity接收到了START信息
2019-01-30 20:47:53.750 D/test: url3 :Thread执行耗时操作中...
2019-01-30 20:47:53.751 D/test: url3 :Thread发送FINISH信息
2019-01-30 20:47:53.751 D/test: Activity接收到了FINISH信息
总结

上面就是利用HandlerThread在子线程中执行串行任务,并反馈到主线程的栗子。总的来说HandlerThread的知识点就是这些,若有错误或者遗漏欢迎指出。

0%