Async task to show an AlertDialog

前端 未结 2 657
北荒
北荒 2020-12-03 19:28

For the past few days, I haven\'t been able to solve an issue with my dialog box. I am running a thread to show the dialog box for 5000ms and removing it. and I am trying to

相关标签:
2条回答
  • 2020-12-03 19:53

    Why you don't use Android AsyncTask? For example:

    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);
    }
    
    0 讨论(0)
  • 2020-12-03 20:01

    Easy: show dialog onPreExecute, register() in doInBackground and hide dialog in onPostExecute. Finally, do new RegisterTask().execute() in your 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
         }
      }
    }
    
    0 讨论(0)
提交回复
热议问题