2011-04-23 78 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

相关问题