2011-04-23 81 views
1

我試圖在Android中的每個GPS定位之間設置一個5分鐘的間隔。我的代碼如下所示:設置每個GPS定位之間的間隔

private void startMonitoring() { 
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 
    locationListener = new LocListener(); 
    if (locationManager.isProviderEnabled(locationManager.GPS_PROVIDER)){ 
     startUpdates(); 
    } else { 
     // I open here the preferences to force the user start the GPS 
    } 
} 

private void startUpdates(){ 
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener); 
} 

public class LocListener implements LocationListener{ 
    @Override 
    public void onLocationChanged(Location loc){ 
    ... 
      locationManager.removeUpdates(locationListener); 
      scheduleUpdates(); 
    } 
    ... 
} 

private void scheduleUpdates(){ 
     // Wait 5 minutes 
     handler.sleep(5 * 60 * 1000); 
     startUpdates(); 
} 

class WaitHandler extends Handler { 
     @Override 
     public void handleMessage(Message message) {} 

     public void sleep (long delayMillis){ 
      this.removeMessages(0); 
      sendMessageDelayed(obtainMessage(0), delayMillis); 
     } 
    } 

我一直在這幾個小時,但我一直沒能找到一個好的解決辦法呢。任何幫助,將不勝感激,

非常感謝你,

回答

1

定義定時器T和處理程序處理,並寫:

t = new Timer(); 
     t.schedule(new TimerTask(){public void run(){handler.post(new Runnable(){public void run(){ 
     //your code here 
}});}}, int delay, int rep); 

延遲是第一次運行前的毫秒數,並且每次運行都會通過代表毫秒(在您的情況中,rep = 1000 * 60 * 5)分離。

+0

它的作品!謝謝! – Ullfoll 2011-04-23 18:30:16

2

也許你應該使用requestLocationUpdate參數: locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5*60*1000, 0, locationListener);

+0

我不能使用它,因爲我需要暫停向GPS請求更新以節省電池,並且這會保持GPS開啓。不管怎樣,謝謝你。 – Ullfoll 2011-04-23 18:19:06

+0

另外,requestLocationUpdate參數只定義了最小值,而不是修正之間的實際時間間隔。 – Noloxs 2012-10-01 10:57:02

相關問題