/**
* 用于启动具有Looper的新线程的方便类。Looper能够被用于创建Handler。但是类仍然需要调用start()方法,才能开启线程
*/
public class HandlerThread extends Thread {
int mPriority; //优先级
int mTid = -1;
Looper mLooper;//Looper对象,可以用于两个线程之间传递信息
public HandlerThread(String name) {
super(name);
mPriority = Process.THREAD_PRIORITY_DEFAULT;
}
/**
* 构造函数:创建一个带有名称和优先级的HandlerThread
*/
public HandlerThread(String name, int priority) {
super(name);
mPriority = priority;
}
/**
* 回调方法,可以被重写,如果需要执行一个Looper的Loop方法
*/
protected void onLooperPrepared() {
}
@Override
public void run() {
mTid = Process.myTid();
Looper.prepare(); //启动一个新的区别于主线程的Looper
synchronized (this) {
mLooper = Looper.myLooper(); //获取刚刚新建的Looper
notifyAll();
}
Process.setThreadPriority(mPriority);
onLooperPrepared();
Looper.loop();
mTid = -1;
}
/**
* 方法返回一个本线程中创建的一个Looper。如果线程没有被启动,或者是isAlive()是false,就返回null。 如果这个线程被启动了,这个方法将会阻塞直到Looper被初始化
* @return The looper.
*/
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;
}
/**
* 退出该线程的Looper
*/
public boolean quit() {
Looper looper = getLooper();
if (looper != null) {
looper.quit();
return true;
}
return false;
}
/**
* 安全的退出Looper对象.
* <p>
* @return True if the looper looper has been asked to quit or false if the
* thread had not yet started running.
*/
public boolean quitSafely() {
Looper looper = getLooper();
if (looper != null) {
looper.quitSafely();
return true;
}
return false;
}
/**
* 返回线程的id. See Process.myTid().
*/
public int getThreadId() {
return mTid;
}
}
后续还会更新HandlerThread的用法和其他相关知识。