【问题标题】:how to stop asnchrounous task when click cancel button单击取消按钮时如何停止异步任务
【发布时间】:2012-09-10 23:27:27
【问题描述】:

我正在使用异步任务将联系人导入文件,它进展顺利,但在启动异步任务后,如果我想在中间取消它,那么如何停止它意味着在停止异步任务之前已经完成的任务应该为 null 并停止异步任务..我的代码在下面请帮助我..

【问题讨论】:

标签: android


【解决方案1】:

可以通过调用 cancel(boolean) 随时取消任务。调用此方法将导致对isCancelled() to return true 的后续调用。调用此方法后,onCancelled(Object) 将在 doInBackground(Object[]) 返回后调用,而不是 onPostExecute(Object)。为确保尽快取消任务,您应始终定期从doInBackground(Object[]) 检查isCancelled() 的返回值,如果可能(例如在循环内)。

【讨论】:

  • 嗨..我正在使用。 cancel.setOnClickListener(new OnClickListener(){ public void onClick(View v) { boolean mayInterruptIfRunning = true; new createCSV().cancel(mayInterruptIfRunning); } });在后台我使用 while (isCancelled()) { if (isCancelled()) { Log.i("################","true value" );休息; } } 返回空值; } 但不工作..:(
  • cancel 是按钮的对象,单击取消按钮时我想停止异步任务以及为什么问题出在 new createCSV().cancel(mayInterruptIfRunning);我没有得到..
  • 在您的活动的 onCreate() 中初始化 AsyncTask 类的对象,并使用相同的对象执行和取消(),你明白了吗..?
  • AsyncTask createCSV = new AsyncTask() { } 像这样,在您的活动中使用 createCSV.execute() 并在 cancelButton 上创建CSV。取消(mayInterruptIfRunning);
【解决方案2】:

我会的 而(!已取消()) 作为while条件。因此,当您按下取消按钮时,请在 AsyncTask 上调用 cancel(true)。这将导致 while 条件为假。然后 doInBackground 将退出。

如果您实现 onCancel,这将在 doInBackground 之后调用,您可以将联系人设置为 null。

希望对您有所帮助。

【讨论】:

    【解决方案3】:

    覆盖方法onCancelled()并在该设置标志canceled = true; 并将这个取消的变量传递给doInBackground中的条件。

    【讨论】:

    • 但是在 doInBackground 完成之前不会调用 onCancelled()。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-10
    相关资源
    最近更新 更多