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
}
As documentations says
so in case if last location return null you must request new on or custom handler