0

我试图通过获取所有侦听器来获取设备位置:

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,但是如何停止所有 Listeners?

谢谢

4

1 回答 1

1

您必须保留您注册的所有位置侦听器的列表,然后在完成后对每个侦听器调用 unregister。要么为每个调用重用相同的侦听器,然后注销一次。

编辑

//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);
}
于 2013-02-07T18:11:57.377 回答