【问题标题】:Not able to cancel with Cancel button in AsyncTask in android无法使用 android 中的 AsyncTask 中的取消按钮取消
【发布时间】:2014-03-25 07:41:47
【问题描述】:

我创建了一个 AsyncTask。

在 onPreExecute() 中创建一个进度对话框。 在创建对话框本身时,取消按钮被添加到对话框中。 在哪个任务被取消。

在 onPostExecute() 中,对话框被关闭。

问题: 我们点击取消按钮的点,我们已经到达 onPostExecute() 这里,我们没有在点击监听器时进入取消按钮。

其中,如果是inBackground(),则正确进入取消按钮的onClick监听器。

如何处理用户点击取消的那一刻,用户进入 onPostExecute(),这就是为什么不能执行 onClick 监听器??

【问题讨论】:

    标签: android android-asynctask cancel-button


    【解决方案1】:

    您可以在 onPostExecute 中检查 boolean 变量。如果它是真的,那么你的工作是否会退出或从该代码返回。您可以在 cancel button 上设置布尔变量。

    喜欢

    boolean canExecute = true;
    

    PostExcute

    while(canExecute){}
    

    并在取消按钮中将canExecute 设置为false

    【讨论】:

      【解决方案2】:

      我认为问题与您描述的不完全一样。 (没有代码不容易……请贴一些代码)

      一旦您到达 onPostExecute 并且当用户单击取消时对话框尚未关闭:取消侦听器已执行,但 asyncTask.cancel(...) 将失败:即它返回 false(因为任务已经执行)。

      如果您需要中断onPostExecute 代码:然后将该代码移动到 AsyncTask.doInBackground 中并保持按钮取消的代码尽可能简单:

      if(asyncTask.cancel(true)){
          dialog.dismiss();
      }else{
          //the asyncTask is already in the onPostExecute
          //the dialog will be dismissed in the onPostExecute... so don't do anything.
      }
      

      让 onPostExecute() 的代码尽可能简单:

      dialog.dismiss();
      

      【讨论】:

        猜你喜欢
        • 2013-11-03
        • 2013-10-14
        • 1970-01-01
        • 2014-02-12
        • 2013-02-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多