异步任务显示AlertDialog

时间:2011-06-27 13:57:50

标签: android android-asynctask builder

2 个答案:

答案 0 :(得分:14)

简单:在onPreExecute中显示对话框doInBackground,注册()并隐藏onPostExecute中的对话框。最后,在new RegisterTask().execute()中进行onclick

 private class RegisterTask extends AsyncTask<Void, Void, Boolean> {
  private final ProgressDialog dialog = new ProgressDialog(YourClass.this);

  protected void onPreExecute() {
     this.dialog.setMessage("Signing in...");
     this.dialog.show();
  }

  protected Boolean doInBackground(final Void unused) {
     return Main.this.register(); //don't interact with the ui!
  }

  protected void onPostExecute(final Boolean result) {
     if (this.dialog.isShowing()) {
        this.dialog.dismiss();
     }
     if (result.booleanValue()) {
     //also show register success dialog
     }
  }
}

答案 1 :(得分:10)

为什么不使用Android AsyncTask? 例如:

public class MyPreloader extends AsyncTask<InputObject, Void, OutputObject>{
private Context context;
private ProgressDialog dialog;

public MyPreloader(Context context){
    this.context = context;
}

@Override
protected void onPreExecute() {
    dialog = new ProgressDialog(context);
    dialog.setMessage("Please wait...");
    dialog.setIndeterminate(true);
    dialog.show();
    super.onPreExecute();
}   

@Override
protected ResponseBase doInBackground(InputObject... params) {
InputObject input = params[0]; 
//some code for background work
    }

@Override
protected void onPostExecute(OutputObject result) {
    if (dialog.isShowing()) {
        dialog.dismiss();
    }
    super.onPostExecute(result);
}