2012-07-26 66 views
3

我想結束從Android設備到Web服務器的HTTP請求,並定期(每分鐘一次)檢查數據庫的特定數據。我無法爲此執行計時器。創建定時器發送HTTP請求定期 - Android

感謝

+1

http://stackoverflow.com/questions/4597690/android-timer-how – Niko 2012-07-26 10:12:34

+0

試試這一個http://stackoverflow.com/questions/9718165/android-timer-task-doesnt-wait-for-the-scheduled-delayed-time/9718376#9718376 – 2012-07-26 10:16:46

回答

10
public class MyActivity extends Activity { 
Timer t ; 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
    t = new Timer(); 
    t.schedule(new TimerTask() { 

     public void run() { 


      //Your code will be here 

     } 
     }, 1000); 

    } 
} 
2

嘗試AlarmManager運行Service。我不建議每分鐘發送一次請求,除非用戶手動觸發該請求。

0

最簡單的方法是循環處理程序:

private Handler iSender = new Handler() { 
    @Override 
    public void handleMessage(final Message msg) { 
     //Do your code here 
     iSender.sendEmptyMessageDelayed(0, 60*1000); 
    } 
}; 

要啓動循環調用這樣一句話:

iSender.sendEmptyMessage(0); 
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 
        //what u want to do.... 
       } 

      } 
     }); 

    } 

}; 

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