2011-08-08 10 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; 

} 
//.... 
} 

런은 처음으로 벌금,하지만 난에 "예약"타이머 딜레이와 두 번째 시간을하려고 할 때, 로그 캣 불평을 :

"이미 예약 된 TimeTask"

타이머를 어떻게 다시 예약 할 수 있습니까?

답변

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; 
    } 
    //... 
} 
관련 문제