在能够取消整个循环的同时循环执行后台网络任务

时间:2014-03-28 04:54:27

标签: android networking timer task runnable

我正在开发一个应用程序,它需要按特定顺序逐个执行网络任务,并且每次执行之间都会有特定时间。

我尝试使用AsyncTask和TimerTask来实现它。

AsyncTask不起作用,因为能够取消它我需要创建一个AsyncTask对象,但如果我这样做,那么我就无法在完成时重新启动任务。

TimerTask在某种程度上起作用,但它非常笨重。尝试取消TimerTask中间操作已经证明是非常困难的,并且我不断地运行两个版本的任务。当我试图将TimerTask分成五个较小的TimerTasks(每个需要完成的操作一个)时,这个问题被放大了。

那么,有没有办法按顺序执行一组后台任务,每次执行之间会有特定时间?

1 个答案:

答案 0 :(得分:0)

import java.util.ArrayList;
import java.util.Collections;

public class RunnableQueue {
    ArrayList<Runnable> queue;
    Runnable[] tasks;
    boolean cancelled;
    double tag;

    public RunnableQueue(Runnable... tasks) {
        this.tasks = tasks;
        this.tag = Math.random();
        queue = new ArrayList<Runnable>();
        Collections.addAll(queue, tasks);
    }

    public void add(Runnable r) {
        queue.add(r);
    }

    public double getTag() {
        return tag;
    }

    public void addToFront(Runnable r) {
        queue.add(0, r);
    }

    public void next() {
        if (queue.size() > 0) {
            new Thread(queue.get(0)).start();
            queue.remove(0);
        }
    }

    public void stop() {
        cancelled = true;
        queue.clear();
    }

    public void resume() {
        if (cancelled) {
            tag = Math.random();
            cancelled = false;
            Collections.addAll(queue, tasks);
            next();
        }
    }

    public boolean isCancelled() {
        return cancelled;
    }
}

这是一个可以与RunnableQueue一起使用的Runnable示例:

Runnable queueTester = new Runnable() {

    @Override
    public void run() {
        double tag = executor.getTag();

        //do some background stuff here

        Log.i("RunnableQueue-test", "queueTester complete. Sleeping...");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if (executor.isCancelled()) {
            Log.i(TAG, "Boolean is false. Not continuing.");
        } else if (executor.getTag() != tag) {
            Log.i(TAG, "Tag has been updated. Not continuing.");
        } else {
            executor.add(this);
            executor.next();
        }
    }
};