如何停止位置监听器

时间:2013-02-07 18:08:11

标签: android location 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);

}

当我想要停止听众时问题就出现了。我试图取消计时器:

gpsTimer.cancel();

但它并没有阻止听众。我想我必须使用locationManager.removeUpdates,但是如何停止所有监听器?

由于

1 个答案:

答案 0 :(得分:1)

您必须保留您注册的所有位置侦听器的列表,然后在完成后调用每个位置侦听器的取消注册。或者只是为每个调用重用相同的侦听器,然后取消注册一次。

修改

//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);
}