有没有办法每隔x分钟获取一次该位置,即使没有变化?

时间:2017-12-27 21:26:55

标签: android location

我正在使用Android Studio。我使用locationManager.requestLocationUpdates(...)来获取位置。

我想做这样的事情:

//print location every 5 minutes
12:10am lat=10.23652 long=21.25441
12:15am lat=10.23652 long=21.25441
12:20am lat=15.21456 long=58.21452
12:25am lat=12.24752 long=27.24587
12:30am lat=12.24752 long=27.24587
12:35am lat=12.24752 long=27.24587
...

我不知道位置是否发生了变化,我只想每隔x分钟打印一次。

1 个答案:

答案 0 :(得分:0)

解决方案可以包含带有postDelayed的Handler。 删除任何回调非常重要!

尝试这样的事情:

private boolean continueLoop = true;
private Handler myHandler = new Handler();

private void startLocationManager() {
    try{
        Log.d(TAG, "startLocationManager - Started");
        // here the delay (in this example it is effectively the interval)
        int minutes = 5;
        int delay = 1000 * 60 * minutes;
        myHandler.postDelayed(mAutoLocationManager, delay);
    }
    catch(Exception ex){
        Log.e(TAG, ex.getMessage());
    }
}

private Runnable mAutoLocationManager = new Runnable() {
    public void run() {
        if(continueLoop){
            // preform the scan for the location coordinates
            startYourLocationCoordinates();

            //re-trigger the call to start a new interval
            startLocationManager();
        {
    }
};

// Make certain that you remove the callback when you leave the activity -- maybe in onPause()
private void stopAutoDownloadManager(){
    try{
        myHandler.removeCallbacks(mAutoLocationManager);
    }
    catch(Exception ex){
        Log.e(TAG, ex.getMessage());
    }
}