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?