【问题标题】:How to display a dialog to wait for user to continue in an AsyncTask?如何显示一个对话框以等待用户在 AsyncTask 中继续?
【发布时间】:2015-04-02 08:31:36
【问题描述】:

我有一个 AsyncTask,它在 doInBackground() 部分做了很多事情,在这些事情之间,我需要等待用户实际做某事才能继续。如何在继续之前弹出一些对话框让用户单击“确定”?

谢谢!

【问题讨论】:

  • 在 Asynctask 结束时,你在等待用户输入吗?

标签: android android-asynctask dialog


【解决方案1】:

在这一堆东西之间,我需要等待用户 在我可以继续之前做一些实际的事情。

你不应该在 doInBackground 方法中这样做,你需要在 onPostExecute();与用户的交互应该在 onPostExecute 中完成。

你可以在这里做什么?

将你的代码分成两部分,在 doInBackground 中执行在后台用户交互之前必须完成的代码,让用户交互在 onPostExecute 中执行此操作,之后剩余的代码你可以使用另一个 AsyncTask。

【讨论】:

    【解决方案2】:
    class LoadData extends AsyncTask<Object, Object, Object>
        {
    
            @Override
            protected Object doInBackground(Object... p_params)
            {
                // Your background code
                return null;
            }
    
    
            @Override
            protected void onPreExecute()
            {
                // Display Progress dialog with cancelable false
                super.onPreExecute();
            }
            @Override
            protected void onPostExecute(Object p_result)
            {
                // Dismiss Progress dialog
                super.onPostExecute(p_result);
            }
        }
    

    【讨论】:

      【解决方案3】:

      如果您想在 doInBackground 部分之间放置等待对话框,那么您可以尝试以下代码:

      @Override
          protected Void doInBackground(Void... params) {
              activity.runOnUiThread(new Runnable() {
      
                  @Override
                  public void run() {
                      final Dialog dialog = new Dialog(activity);
                      dialog.setTitle("Demo");
                      Button button = new Button(activity);
                      button.setText("Press For Process..");
                      dialog.setContentView(button);
                      button.setOnClickListener(new OnClickListener() {
      
                          @Override
                          public void onClick(View v) {
                              Toast.makeText(activity, "Perform Task",
                                      Toast.LENGTH_LONG).show();
                              // You can perform task whatever want to do after
                              // on user press the button
                              dialog.dismiss();
                          }
                      });
      
                      dialog.show();
                  }
              });
              return null;
          }
      

      【讨论】:

      • 这里提供的所有答案中最好的!应该被接受
      猜你喜欢
      • 2015-02-02
      • 2016-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-21
      • 1970-01-01
      • 1970-01-01
      • 2018-04-15
      相关资源
      最近更新 更多