How to stop location listeners

雨燕双飞 提交于 2021-02-11 12:53:27

问题


I'm trying to get the devices location by getting all listeners:

LocationManager locationManager = (LocationManager) myContext.getApplicationContext()
        .getSystemService(Context.LOCATION_SERVICE);


for (String s : locationManager.getAllProviders()) {

    locationManager.requestLocationUpdates(s, checkInterval,
            minDistance, new LocationListener() {


                @Override
                public void onProviderEnabled(String provider) {

                }

                @Override
                public void onProviderDisabled(String provider) {

                }

                @Override
                public void onLocationChanged(Location location) {
                    // if this is a gps location, we can use it
                    if (location.getProvider().equals(
                            LocationManager.GPS_PROVIDER)) {
                        doLocationUpdate(location, true);
                        stopGPS();
                    }
                }

                @Override
                public void onStatusChanged(String provider,
                        int status, Bundle extras) {
                    // TODO Auto-generated method stub

                }
            });

        gps_recorder_running = true;
}

// start the gps receiver thread
gpsTimer.scheduleAtFixedRate(new TimerTask() {

    @Override
    public void run() {
        Location location = getBestLocation();
doLocationUpdate(location, false);
if ((System.currentTimeMillis()-startMillis)>maxCheckTime){stopGPS();}

    }
}, 0, checkInterval);

}

The problem comes when I want to stop the Listeners. I tried to cancel the timer:

gpsTimer.cancel();

But it doesn't stop the Listeners. I think I have to use locationManager.removeUpdates, but how do I stop all Listeners?

Thanks


回答1:


You must keep a list of all the location listeners you register and then call unregister with each of them when you are done. Either that or just reuse the same listener for each call and then unregister it once.

Edit

//Make the following line a field in your class
List<LocationListener> myListeners = new ArrayList<LocationListener>();

for (String s : locationManager.getAllProviders()) {
LocationListener listener = new LocationListener() { .... }; //I'm cutting out the implementation here
myListeners.add(listener);

 locationManager.requestLocationUpdates(s, checkInterval,
            minDistance, listener);
}


来源:https://stackoverflow.com/questions/14757980/how-to-stop-location-listeners

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!