Android:重新启动计时器失败

时间:2011-08-08 19:39:51

标签: android

我正在尝试每隔X分钟下载一个网址的一些数据。这是从服务运行。

我的服务类中有以下内容:

public class CommandsService extends Service {
    public String errormgs;

// in miliseconds
static final long DELAY = 60*1000;

public Timer timer;

public int onStartCommand (Intent intent, int flags, int startId) {

    TimerTask task= new TimerTask (){
        public void run(){
            //do what you needs.
            processRemoteFile();

            // schedule new timer
            // following line gives error
            timer.schedule(this, DELAY);
        }
    };
    timer = new Timer();
    timer.schedule(task, 0);

    return START_STICKY;

} 
 //....
}

第一次运行正常,但是当我尝试使用DELAY第二次“安排”计时器时,LogCat会抱怨:

“已安排TimeTask”

我怎样才能重新安排计时器?

2 个答案:

答案 0 :(得分:1)

TimerTask是一次性项目。它不能重新安排或重复使用;您需要在需要时动态创建新实例。

答案 1 :(得分:0)

怎么样:

public class CommandsService extends Service {
    public String errormgs;

    // in miliseconds
    static final long DELAY = 60*1000;

    public Thread thread;

    public int onStartCommand (Intent intent, int flags, int startId) {

        Runnable runnable = new Runnable () {
            public void run() {
                while (<condition>) {
                    //do what you needs.
                    processRemoteFile();

                    try {
                        Thread.sleep(DELAY);
                    } catch (InterruptedException e) {
                    }
                }
            }
        };
        thread = new Thread(runnable);
        thread.start();

        return START_STICKY;
    }
    //...
}