我在一个非常基本的处理程序教程中遇到了这段代码。代码工作正常,但我不明白为什么我必须使用 Handler progressDialog.dismiss()
???我删除了 Handler 部分并放入 progressDialog.dismiss()
方法中run()
,它工作正常。那为什么要用Handler???
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class HandlerThread extends Activity{
private Button start;
private ProgressDialog progressDialog;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
start = (Button) findViewById(R.id.Button01);
start.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
fetchData();
}
});
}
protected void fetchData() {
// TODO Auto-generated method stub
progressDialog = ProgressDialog.show(this, "", "Doing...");
new Thread() {
public void run() {
try {
Thread.sleep(8000);
} catch (InterruptedException e) {
}
messageHandler.sendEmptyMessage(0);
}
}.start();
}
private Handler messageHandler = new Handler() {
public void handleMessage(Message msg) {
super.handleMessage(msg);
progressDialog.dismiss();
}
};
}