Reputation: 75
I am using Network Provider to get the last known location of the user. When I tested it, It was working perfectly in one of my phones, but latitude and longitude is returning null on another phone. Is there an alternative to location manager to get a more consistent result. Or is there some other bug in my code
Here is my Permission checking Code:
if (ContextCompat.checkSelfPermission(
applicationContext,
Manifest.permission.ACCESS_COARSE_LOCATION
) != PackageManager.PERMISSION_GRANTED
) {
AlertDialog.Builder(this)
.setCancelable(false)
.setTitle("Please Grant Location Permissions")
.setPositiveButton("Ok", null)
.show()
ActivityCompat.requestPermissions(
this,
arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION),
101
)
}
And my location request code
longitude =
locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER)?.longitude
latitude =
locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER)?.latitude
val geocoder = Geocoder(this)
if (latitude != null && longitude != null) {
val addresses: List<Address> = geocoder.getFromLocation(latitude, longitude, 1)
val cityName = addresses[0].subAdminArea
}
Upvotes: 0
Views: 237
Reputation: 1151
As documentations says
Gets the last known location from the given provider, or null if there is no last known location. The returned location may be quite old in some circumstances, so the age of the location should always be checked. This will never activate sensors to compute a new location, and will only ever return a cached location. See also getCurrentLocation(String, CancellationSignal, Executor, Consumer) which will always attempt to return a current location, but will potentially use additional power in the course of the attempt as compared to this method. Params: provider – a provider listed by getAllProviders() Returns: the last known location for the given provider, or null if not available Throws: SecurityException – if no suitable permission is present IllegalArgumentException – if provider is null or doesn't exist
so in case if last location return null you must request new on or custom handler
Upvotes: 1