Search code examples
androidgpslocationmanagerlocationlistener

Unsubscribe LocationListener from LocationManager after getting location data


For some reason when I add removeUpdates() after the requestLocationUpdates() method, I don't obtain any location data at all. Am I not unsubscribing correctly?

LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER, 5000, 1, mlocListener);
mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 5000, 1, mlocListener);
mlocManager.removeUpdates(mlocListener);


public class MyLocationListener implements LocationListener
    {
        @Override
        public void onLocationChanged(Location loc)
        {
            loc.getLatitude();
            loc.getLongitude();
            String text = "My current location is: " +
            "Latitude = " + loc.getLatitude() +
            "Longitude = " + loc.getLongitude();
            System.out.println("FINISHED:");
            Toast.makeText( getApplicationContext(),
                    text,
                    Toast.LENGTH_SHORT).show();

        }
}

Solution

  • I ended up creating a Thread inside my LocationHandler with a nested while which kept looping until a GPS location was found. When found I unsubscribed my LocationListener.