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

问题描述 投票:0回答:1

我正在使用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分钟打印一次。

android location
1个回答
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());
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.