目录
前言
众所周知如果想要在Android中执行耗时操作需要新建一个线程然后在该线程中实现,但是如果出现一种需要我们频繁进行耗时操作的业务,那我们再频繁的创建线程无疑会使性能降低,而Android SDK为我们提供了一个循环线程的框架刚好可以帮助我们解决这个问题,它就是HandlerThread。
原理
HandlerThread继承了Thread,集成了Looper和MessageQueue,在内部实现了一个消息队列,队列中的消息是顺序执行的因此线程是安全的,HandlerThread内部机制确保了在创建Looper和发送消息之间不存在竞态条件,这个是通过HandlerThread.getLooper()实现为一个阻塞操作实现的,只有当HandlerThread准备好接收消息消息之后才会返回。
public 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() {
}
@Override
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实例
public class MainActivity extends AppCompatActivity {
private HandlerThread mHandlerThread;
private Handler mBgHandler;
@Override
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() {
@Override
public boolean handleMessage(Message message) {
switch (message.what){
case 0:
// 执行操作
break;
}
return false;
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
mHandlerThread.quit();
}
}
- 对外隐藏Handler(需要继承HandlerThread并在onLooperPrepared方法中对Handler进行实例化)
public class MyHandlerThread extends HandlerThread {
private Handler mHandler;
public MyHandlerThread(String name) {
super(name);
}
@Override
protected void onLooperPrepared() {
super.onLooperPrepared();
mHandler=new Handler(getLooper(), new Handler.Callback() {
@Override
public boolean handleMessage(Message message) {
switch (message.what){
case 1:
Log.e("测试","executeOne"+currentThread().getName());
break;
case 2:
Log.e("测试","executeTwo"+currentThread().getName());
break;
}
return false;
}
});
}
public void executeOne(){
mHandler.sendEmptyMessage(1);
}
public void executeTwo(){
mHandler.sendEmptyMessage(2);
}
}
Activity中调用
public class MainActivity extends AppCompatActivity {
private TextView tvMainactivityTest;
private MyHandlerThread myHandlerThread;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvMainactivityTest = (TextView) findViewById(R.id.tv_mainactivity_test);
initHandler();
}
private void initListener() {
tvMainactivityTest.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
myHandlerThread.executeOne();
}
});
}
private void initHandler() {
myHandlerThread=new MyHandlerThread("workThread");
myHandlerThread.start();
}
}