第一种方法是用Thread+handler来实现,适用于大型框架的逻辑处理
final int PROGRESS_DIALOG = 0;
ProgressThread progressThread;
ProgressDialog progressDialog;
Activity activity;
protected Dialog onCreateDialog(int id) {
switch (id) {
case PROGRESS_DIALOG:
progressDialog = new ProgressDialog(activity);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setMessage("请稍等...");
progressDialog.setCancelable(true);
progressThread = new ProgressThread(handler);
progressThread.start();
return progressDialog;
default:
return null;
}
}
private class ProgressThread extends Thread {
// 由于Handler运行在主线程中(UI线程中),它与子线程可以通过Message对象来传递数据,
Handler mHandler;
ProgressThread(Handler h) {
mHandler = h;
}
public void run() {
String buffer = "";
Message msg = mHandler.obtainMessage();
Bundle b = new Bundle();
b.putString("buffer", buffer);
msg.setData(b);
mHandler.sendMessage(msg);
}
}
final Handler handler = new Handler() {
public void handleMessage(Message msg) {
// 获取数据
String buffer = msg.getData().getString("buffer");
activity.removeDialog(PROGRESS_DIALOG);
}
};
第二种是:AsynTask,适用于小型简单的处理:
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
MyAsyTast asytast =new MyAsyTast();
asytast.execute();
}
private class MyAsyTast extends AsyncTask<Integer, String, String>{
private ProgressDialog dialog;
@Override
protected String doInBackground(Integer... params) {
if (isCancelled()) {
return null;
}
//处理事务之前的操作,或者是接收获取数据等待处理
return null;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (GrouponOrderCheck01.this.isFinishing()) {
return ;
}
if (dialog!=null) {
dialog.cancel();
}
if (isCancelled()) {
return;
}
//处理事件
}
@Override
protected void onPreExecute() {
super.onPreExecute();
dialog =DialogHelper.createProgressDialog(GrouponOrderCheck01.this);
}
@Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
if (isCancelled()) {
return;
}
}
}