AsyncTask 永远循环 Android

AsyncTask forever loop in Android

目前我使用这段代码来执行任务:

AsyncTask<Object, Integer, Void> task = new Task(getApplicationContext(), this.findViewById(android.R.id.content));

task.execute();

现在,我想在 while 循环中永远重复这个任务,当任务完成后我会启动一个新任务..

我该如何继续?

我知道要获取我可以使用的任务状态:task.getStatus(); 但是在 ?

之后

来自http://developer.android.com/reference/android/os/AsyncTask.html

The task can be executed only once (an exception will be thrown if a second execution is attempted.)

因此您只能使用 AsyncTask 实例一次。

您当然可以在 onPostExecute 上创建另一个任务,但这是一种不好的做法,因为 AsyncTasks 旨在用于执行短任务:

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 package such as Executor, ThreadPoolExecutor and FutureTask.

我不知道你的代码的细节,但这是一个递归的解决方案,

AsyncTask 有 onPostExecute 方法。只需在该方法中再次调用另一个任务。但是,如果任务完成(你用任何标志控制它),启动新的 activity

protected void onPostExecuteTask(Object result) {
    if(!flag){
        //Run the Task again
        }else{
        //Start the new activity
        }
}