-2

I am trying to access the GPS position of the users device and seem to be getting nowhere.

In my class I have the following code, it checks to see if the GPS Provider is enabled and then attempts to get the users last known location.

It recognizes that the GPS provider is enabled but I get nothing when I try to get the last known location, myLocation always comes back as null.

// try to get GPS location
LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
final boolean gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

if (gpsEnabled) {

    //request for location updates
    LocationListener locationListener = new MyLocationListener();
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 100, 0, locationListener);

    Location myLocation;
    myLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

    if (myLocation != null) {
        //we have a location!!
    }

} // end if gps enabled

Here is the code from the LocationListener

public class MyLocationListener implements LocationListener
{
    public void onLocationChanged(Location location) {
        location.getLatitude();
        location.getLongitude();
        // TODO get accuracy, direction and speed.
        // this method is unfinished...
    }
}

And here is the permissions from the manifest file

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

Obviously there is something that I am overlooking to get the device location.. Why does the Last Known Location always return null?

matt.
  • 2,355
  • 5
  • 32
  • 43

1 Answers1

1

Couple of things:

  1. In your LocationListener you aren't doing anything with location. E.g. you can save location in a variable and use later.
  2. LocationManager.getLastKnownLocation can return null if either the provider is disabled or device does not have any known location.
  3. While using emulator you can mock locations. Read http://developer.android.com/guide/topics/location/strategies.html#MockData
  4. To mock on devices you can use "Fake GPS" app and allow mock location in Settings

Hope it helps.

Sangharsh
  • 2,999
  • 2
  • 15
  • 27