【问题标题】:Is doInBackground Cancelled when dialog dismisses?对话框关闭时是否取消了doInBackground?
【发布时间】:2017-10-15 03:50:43
【问题描述】:

我在 AsyncTask 中有一个自定义进度对话框,它充当下载进度,我想在按下自定义取消按钮时中断 doInBackground。似乎当对话框关闭时,doInBackground 恢复没有任何问题!

【问题讨论】:

    标签: android android-asynctask


    【解决方案1】:
    I want to interrupt doInBackground when my custom cancel button pressed. 
    

    => 在取消按钮单击事件中调用 AsyncTask 的 cancel() 方法。现在这还不足以取消 doInBackground() 进程。

    例如:

     asyncTask.cancel(true);
    

    要使用 cancel() 方法通知您已取消 AsyncTask,您必须使用 doInBackground() 内的 isCancelled() 来检查它是否已取消

    例如:

    protected Object doInBackground(Object... x) 
    {
      // do your work...
    
       if (isCancelled())  
           break;
    
    } 
    

    【讨论】:

      【解决方案2】:

      您可以从对话框的取消事件中调用AsyncTask.cancel(true)。为此,您确实需要对 AsyncTask 的引用,这可能是在任务启动时初始化的实例变量。然后在asyncTask.doInBackground() 方法中可以检查isCancelled(),或者覆盖onCancelled() 方法并在那里停止正在运行的任务。

      例子:

      //Asynctask instance variable
      private YourAsyncTask asyncTask;
      
      //Starting the asynctask
      public void startAsyncTask(){
         asyncTask = new YourAsyncTask();
         asyncTask.execute();
      }
      
      //Dialog code
      loadingDialog = ProgressDialog.show(ThisActivity.this,
                                                     "",
                                                     "Loading. Please wait...",
                                                     false,
                                                     true,
                                                     new OnCancelListener()
                                                     {
      
                                                       @Override
                                                       public void onCancel(DialogInterface dialog)
                                                       {
                                                         if (asyncTask != null)
                                                         {
                                                           asyncTask.cancel(true);
                                                         }
                                                       }
                                                     });
      

      编辑:如果您从 AsyncTask 内部创建对话框,则代码不会有很大不同。您可能不需要实例变量,我认为您可以在这种情况下调用 YourAsyncTask.this.cancel(true)。

      【讨论】:

        猜你喜欢
        • 2012-01-08
        • 1970-01-01
        • 1970-01-01
        • 2018-02-09
        • 2021-12-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多