HandlerThread继承于Thread,所以它本质就是个Thread。与普通Thread的差别就在于,主要的作用是建立了一个线程,并且创立了消息队列,有来自己的looper,可以让我们在自己的线程中分发和处理消息。故不能够直接操作主线程ui,否则会出现以下错误:
only the original thread that created a view hierarchy can touch its views
1)首先创建looper对象
private static final int MSG_LOAD_DATA = 0;
private static final int MSG_COMMIT_DATA = 1;
private static HandlerThread mThread = new HandlerThread("greenThread");
static {
mThread.start();
}
private Callback mCallback = new Callback() {
@Override
public boolean handleMessage(Message msg) {
switch (msg.what) {
case MSG_LOAD_DATA:
getMessage();
break;
case MSG_COMMIT_DATA:
CommitPassword();
break;
default:
break;
}
return true;
}
};
private Handler mHandler = new Handler(mThread.getLooper(), mCallback);
2)之后,便可以通过handler进行消息的传递了,如下:
Message msg = mHandler.obtainMessage();
mHandler.removeMessages(MSG_LOAD_DATA);
mHandler.sendEmptyMessageDelayed(MSG_LOAD_DATA, 1 * 300L);
3)延迟操作:
实现runable接口,或者继承thread类,或者继承AsyncTask都可以,如AsynTask:
class Task extends AsyncTask<Void, Void, Void> {
protected Void doInBackground(Void... params) {
Thread.sleep(1000);
}
protected void onPostExecute(Void result) {
result.setText("dddd");
}
}
主线程--->new Task().execute();