一、Class Overview
Class used to run a message loop for a thread. Threads by default do not have a message loop associated with them; to create one, callprepare()
in the thread that is to run the loop, and thenloop()
to have it process messages until the loop is stopped.
Most interaction with a message loop is through theHandler
class.
This is a typical example of the implementation of a Looper thread, using the separation ofprepare()
andloop()
to create an initial Handler to communicate with the Looper.
class LooperThread extends Thread { public Handler mHandler; public void run() { Looper.prepare(); mHandler = new Handler() { public void handleMessage(Message msg) { // process incoming messages here } }; Looper.loop(); } }
当你的线程想拥有自己的MessageQueue的时候先Looper.prepare(),然后Looper.loop();
参照源码:
这段代码就是通过ThreadLocal来产生一个Looper对象做为线程局部变量,然后调用Looper.loop()则是取出Looper对象中的MessageQueue进行消息循环了,这样形成了这个线程的消息队列。 一般情况下只会有主线程会调用prepare方法(ActivityThread的main函数)。 |
四、开发过程中遇到的情况
btnConfirm.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
progressDialog = ProgressDialog.show(
EverydayCheckActivity.this, "提示", "正在上传排查信息");
alertDialog = new AlertDialog.Builder(
EverydayCheckActivity.this)
.setTitle("提示")
.setMessage("排查信息上传成功,是否下发通知单!")
.setPositiveButton("确定",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
Intent intent = new Intent();
intent.setClass(
EverydayCheckActivity.this,
NotificationTableActivity.class);
// EverydayCheckActivity.this
// .startActivity(intent);
Toast.makeText(
EverydayCheckActivity.this,
"下发通知单成功", 3000).show();
}
}).setNegativeButton("取消", null).create();
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
progressDialog.dismiss();
Looper.prepare();
alertDialog.show();
Looper.loop();
}
}, 3000);
}
});
dismiss不通过消息机制实现,而show通过消息机制实现