i dont understand why locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
return the location null. I gave all permission but its reutning null
.
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
I had this exact same problem. It was because my device was not storing a last known location. I simply went on to Google Maps and pinpointed my location with GPS, then a value was returned for getLastKnownLocation()
You can request location updates like this
mLocationManager.requestLocationUpdates(myProvider, 0, 0, locationListener);
then on the first callback in locationListener.onLocationChanged
set your coordinates. Just don't forget to call mLocationManager.removeUpdates(locationListener)
Accoding to the documentation, it returns null, if the device is not aware of the last known location. Probably the GPS can not locate you. It takes about a minute or more, anyway. So try to go outside, under the clear sky, away from tall buildings, and wait until GPS can locate you.
I used this method for get location i think it will help you
private void startReceivingLocationUpdates() {
if (mLocationManager == null) {
mLocationManager = (android.location.LocationManager)
mContext.getSystemService(Context.LOCATION_SERVICE);
}
if (mLocationManager != null) {
try {
mLocationManager.requestLocationUpdates(
android.location.LocationManager.NETWORK_PROVIDER,
1000,
0F,
mLocationListeners[1]);
}
catch (SecurityException ex)
{
Log.i(TAG, "fail to request location update, ignore", ex);
}
catch (IllegalArgumentException ex)
{
Log.d(TAG, "provider does not exist " + ex.getMessage());
}
try {
mLocationManager.requestLocationUpdates(
android.location.LocationManager.GPS_PROVIDER,
1000,
0F,
mLocationListeners[0]);
if (mListener != null) mListener.showGpsOnScreenIndicator(false);
}
catch (SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex); }
catch (IllegalArgumentException ex) {
Log.d(TAG, "provider does not exist " + ex.getMessage()); }
Log.d(TAG, "startReceivingLocationUpdates");
}
}
When you use GPS as provider then it gives your result with in 1 to 2 mnts so you have to contentiously check for that when get location stop and Network Provider gives you immediate locationwhen you request. So you dont get immediate Location lat lon in GPS provider.
GPS take 1 to 2 only first time then after it will give location you on call...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With