2011-08-08 5 views
0

私は毎分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で2回目をしようとすると、LogCatが文句を:

「TimeTask already scheduled」

Timerを再スケジュールするにはどうすればよいですか?

答えて

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; 
    } 
    //... 
} 
関連する問題