Has*_*ssa 11 android geocoding kotlin deprecation-warning android-tiramisu
我收到一条消息,表明此函数(或其构造函数)已被弃用。该函数有一个新的构造函数,它接受附加参数'Geocoder.GeocodeListener listener',但该新构造函数需要 API 级别 33 及以上。对于较低的API级别我应该做什么,解决方案是什么?
Sac*_*hin 12
官方文档- 使用getFromLocation(double, double, int, android.location.Geocoder.GeocodeListener)来避免阻塞等待结果的线程。
例子:
//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)
}
})
Run Code Online (Sandbox Code Playgroud)
我认为处理这种弃用的最干净的方法是将 getFromLocation 移动到新的扩展函数中并添加 @Suppress("DEPRECATION") ,如下所示:
@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)
}
}
Run Code Online (Sandbox Code Playgroud)
这是如何使用:
Geocoder(requireContext(), Locale("in"))
.getAddress(latlng.latitude, latlng.longitude) { address: android.location.Address? ->
if (address != null) {
//do your logic
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12996 次 |
| 最近记录: |