2012-03-15 86 views
1

定時器任務不會等待預定的延遲時間。 我想延遲網絡檢查10秒,但它會在幾秒鐘內執行操作,無需等待。任何幫助,將不勝感激。Android定時器任務不會等待預定的延遲時間

int i = 0; 
public void timertask() 
    { 

     while(i < 5){ 

     Handler handler = new Handler(); 
     handler.postDelayed(new Runnable() { 
       public void run() { 
       if(isNetworkConnected()) // Some method to check net connection 
       { 
        download(); //Method to download 
       } 
      } 
     }, 10000); 

     System.out.println("i = "+i); 
     i++; 
     } 

    } 

回答

1

試試這個。

TimerTask doAsynchronousTask; 
    final Handler handler = new Handler(); 
    Timer timer = new Timer(); 

    doAsynchronousTask = new TimerTask() { 

     @Override 
     public void run() { 

      handler.post(new Runnable() { 
       public void run() { 
        if(isOnline){// check net connection 
        download(); //Method to download 
        } 

       } 
      }); 

     } 

    }; 

    timer.schedule(doAsynchronousTask, 0, 10000);// execute in every 10 s 
+0

Thanks @kaluwila.These代碼片段適合我。 – 2012-03-15 13:00:43