如何多次执行AsyncTask?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (14)

在我的活动中,我使用了一个从AsyncTask扩展的类和一个参数,它是AsyncTask的一个实例。当我打电话的时候mInstanceOfAT.execute("")一切都很好。但是,当我按下一个更新按钮,再次调用AsyncTask时,应用程序就会崩溃(以防网络作业不起作用)。因为这样就出现了一个异常,上面写着

Cannot execute task: the task has already been executed (a task can be executed only once)

我尝试为AsycTask的实例调用Cancel(True),但它也不起作用。到目前为止,唯一的解决方案是创建AsynTask的新实例。这是正确的方式吗?

谢谢

提问于
用户回答回答于

AsyncTask实例只能使用一次。

相反,只需调用您的任务就像new MyAsyncTask().execute("");

来自AsyncTask API文档:

用户回答回答于

例子:

class GetDataFromServerTask extends AsyncTask<Input, Result, Void> {

    private final ReentrantLock lock = new ReentrantLock();
    private final Condition tryAgain = lock.newCondition();
    private volatile boolean finished = false;

    @Override
    protected Void doInBackground(Input... params) {

        lock.lockInterruptibly();

        do { 
            // This is the bulk of our task, request the data, and put in "result"
            Result result = ....

            // Return it to the activity thread using publishProgress()
            publishProgress(result);

            // At the end, we acquire a lock that will delay
            // the next execution until runAgain() is called..
            tryAgain.await();

        } while(!finished);

        lock.unlock();
    }

    @Override
    protected void onProgressUpdate(Result... result) 
    {
        // Treat this like onPostExecute(), do something with result

        // This is an example...
        if (result != whatWeWant && userWantsToTryAgain()) {
            runAgain();
        }
    }

    public void runAgain() {
        // Call this to request data from the server again
        tryAgain.signal();
    }

    public void terminateTask() {
        // The task will only finish when we call this method
        finished = true;
        lock.unlock();
    }

    @Override
    protected void onCancelled() {
        // Make sure we clean up if the task is killed
        terminateTask();
    }
}

当然,这比ASyncTask的传统用法稍微复杂一些,您可以放弃使用公布进展()用于实际进度报告。但是,如果内存是您关心的问题,那么这种方法将确保在运行时只有一个ASyncTask留在堆中。

扫码关注云+社区