I've received a message that this function (or it's constructor) has been deprecated. There's a new constructor of that function that accepts an additional parameter 'Geocoder.GeocodeListener listener'
but that new constructor requires an API Level 33 and above. What should I do for the lower API levels, what's the solution?
Since this is deprecated in API level 33, I believe this is the only option for lower API levels.
I think the cleanest way to handle this deprecation is move getFromLocation into new extension function and add @Suppress("DEPRECATION") like this:
@Suppress("DEPRECATION")
fun Geocoder.getAddress(
latitude: Double,
longitude: Double,
address: (android.location.Address?) -> Unit
) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
getFromLocation(latitude, longitude, 1) { address(it.firstOrNull()) }
return
}
try {
address(getFromLocation(latitude, longitude, 1)?.firstOrNull())
} catch(e: Exception) {
//will catch if there is an internet problem
address(null)
}
}
And this is how to use:
Geocoder(requireContext(), Locale("in"))
.getAddress(latlng.latitude, latlng.longitude) { address: android.location.Address? ->
if (address != null) {
//do your logic
}
}
The Official Doc - Use getFromLocation(double, double, int, android.location.Geocoder.GeocodeListener) instead to avoid blocking a thread waiting for results.
Example:
//Variables
val local = Locale("en_us", "United States")
val geocoder = Geocoder(this, local)
val latitude = 18.185600
val longitude = 76.041702
val maxResult = 1
//Fetch address from location
geocoder.getFromLocation(latitude,longitude,maxResult,object : Geocoder.GeocodeListener{
override fun onGeocode(addresses: MutableList<Address>) {
// code
}
override fun onError(errorMessage: String?) {
super.onError(errorMessage)
}
})
Method getFromLocationName
still exists, but now expects "bounding box" parameters lowerLeftLatitude
, lowerLeftLongitude
, upperRightLatitude
, upperRightLongitude
.
Setting the "bounding box" to the view boundary coordinates should work.
@SuppressWarnings({"deprecation", "RedundantSuppression"})
...
Geocoder geoCoder = new Geocoder(requireContext());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
geoCoder.getFromLocationName(
geocode, maxResults,
lowerLeftLatitude, lowerLeftLongitude,
upperRightLatitude,upperRightLongitude,
addresses -> {
Address bestMatch = (addresses.isEmpty() ? null : addresses.get(0));
updatePosition(item, bestMatch);
});
} else {
try {
List<Address> addresses = geoCoder.getFromLocationName(geocode, maxResults);
Address bestMatch = (addresses.isEmpty() ? null : addresses.get(0));
updatePosition(item, bestMatch);
} catch (IOException e) {
if (mDebug) {Log.e(LOG_TAG, e.getMessage());}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.