I tried to get a location for my android app but getLastKnownLocation
always returns null
and onLocationChanged
is never called. I use the following permissions for my app:
ACCESS_NETWORK_STATE,
ACCESS_FINE_LOCATION ACCESS_COARSE_LOCATION.
GPS and internet are turned on, on my device on. Also I tried different values for requestLocationUpdates
.
locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
locationManager.removeUpdates(this);
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled)
{
// no network provider is enabled
}
else
{
hasGPS = true;
location = null;
if (isGPSEnabled)
{
if (location == null)
{
locationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if (locationManager != null)
{
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null)
{
lat = location.getLatitude();
lng = location.getLongitude();
}
}
}
}
if (isNetworkEnabled && location == null)
{
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if (locationManager != null)
{
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null)
{
lat = location.getLatitude();
lng = location.getLongitude();
}
}
}
}