2011-08-08 67 views
0

我試圖每X分鐘下載一次url的一些數據。這是從服務運行。Android:重新啓動計時器失敗

我在服務類中的以下內容:

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的抱怨:

「已安排時間任務」

我該如何重新安排計時器?

回答

1

TimerTask是一次性使用的物品。它不能被重新安排或重新使用;您需要隨時創建新實例。

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; 
    } 
    //... 
}