0

I want my code to wait for mGPS.GotLocaton to be true (set when the onLocationChanged event is fired)

public class GPSManager  {
    Context MyContext;
    boolean GotLocation = false;
    Location CurrentLocation;
    LocationManager locationManager;

    LocationListener locationlistener = new LocationListener() {
        public void onLocationChanged(Location location) {
            // Called when a new location is found by the network location provider.
            GotLocation = true;
            locationManager.removeUpdates(locationlistener);
        }

        public void onStatusChanged(String provider, int status, Bundle extras) {}

        public void onProviderEnabled(String provider) {}

        public void onProviderDisabled(String provider) {}
    };

    public GPSManager(Context context){
        this.MyContext = context;
        locationManager = (LocationManager) MyContext.getSystemService(Context.LOCATION_SERVICE);
    }

    public void GetCurrentLocation(){
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationlistener);
        GotLocation = false;
    }
}

Is called by:

    myGPS.GetCurrentLocation();
    do{
    }while (!myGPS.GotLocation);

But it doesn't wait/loop - what am I missing.

Mattias Isegran Bergander
  • 11,811
  • 2
  • 41
  • 49
James
  • 1
  • 3

2 Answers2

1

Probably becuase you already got a Location response immediately when adding the LocationListener.

That's some strange code there though. Consider using a callback instead.

For further information on location stuff see this android developer blog entry:

http://android-developers.blogspot.co.uk/2011/06/deep-dive-into-location.html

Or even better, use this library that solves it all for you:

http://code.google.com/p/little-fluffy-location-library/

Mattias Isegran Bergander
  • 11,811
  • 2
  • 41
  • 49
0

in which thread do you call the loop of getting the location?

if it's in the main thread , it's very wrong , since the locationlistener only gets the events run on this thread , but since this thread is in the loop , it will never get there so you are in an infinite loop , which also causes ANR in about 5 seconds or so.

the way the locationlistener works is by using the observer design pattern - when it has something to give you , it will . you can't simply ask it again and again . the only similar thing you can use is to get the last location that it has , using getLastKnownLocation .

android developer
  • 114,585
  • 152
  • 739
  • 1,270