【问题标题】:Cancel method from inside AsyncTaskAsyncTask 内部的 Cancel 方法
【发布时间】:2014-12-08 05:50:39
【问题描述】:

我有一个 AsyncTask 可以访问另一个类中的静态方法。此方法从 Internet 获取文件,因此它具有 URL 连接。 问题是,在某些情况下我必须中断 AsyncTask。我可以通过将任务设置为 .cancel(true) 来做到这一点。但问题是,我必须想办法中断该方法,在他的 doInBackground 方法中调用 AsyncTask。 我该如何存档?

【问题讨论】:

  • 我不确定我理解你想要什么,但听起来你想在 doInBackground 内部取消任务。你仍然可以使用cancel(true) 来做到这一点
  • 听起来你想对你的 URL 连接做一个 .disconnect() 。只需在 Async 上监听 .cancel() ,然后 .disconnect() 连接即可。

标签: android android-asynctask cancellation


【解决方案1】:

正如开发者所说here

    AsyncTask is designed to be a helper class around Thread and Handler and does not
    constitute a generic threading framework. AsyncTasks should ideally be used for short
    operations (a few seconds at the most.) If you need to keep threads running for long
    periods of time, it is highly recommended you use the various APIs provided by the
    java.util.concurrent pacakge such as Executor, ThreadPoolExecutor and FutureTask.

所以最好使用线程而不是Asynctask

当你需要停止你的线程调用myThread.interrupt();

在您的线程中,在每个关键部分之前检查 Thread.interrupted();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多