从AsyncTask内部取消方法

时间:2014-10-13 15:41:03

标签: android android-asynctask cancellation

我有一个AsyncTask,可以在另一个类中访问静态方法。此方法从Internet获取文件,因此它具有URL连接。 问题是,在某些情况下我必须中断AsyncTask。我可以通过将任务设置为.cancel(true)来完成此操作。但问题是,我必须找到一种方法来中断该方法,在他的doInBackground方法中调用AsyncTask。 我怎么能达到这个目的呢?

1 个答案:

答案 0 :(得分:0)

正如开发人员所说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();