【发布时间】:2019-08-11 09:48:30
【问题描述】:
我有一个场景,我想显示用户当前的天气数据,因为我正在获取他/她当前的纬度/经度并对其进行反向地理编码以获取城市名称。获得城市名称后,我将拨打网络电话并显示天气数据。除此之外,我还需要执行许多定位操作。
所以我创建了一个名为LocationUtils.kt 的类。我正在关注 MVVM 架构,想知道哪个是调用LocationUtils 方法的理想层,是view 层还是viewmodel 层或data 层。因为FusedLocationProvider 需要context,如果我在ViewModel 中使用它,它会泄漏。那么如何解决这个问题呢?
LocationUtils.kt:
class LocationUtils {
private lateinit var fusedLocationClient: FusedLocationProviderClient
private fun isLocationEnabled(weakContext: Context?): Boolean {
return when {
Build.VERSION.SDK_INT >= Build.VERSION_CODES.P -> {
// This is new method provided in API 28
val locationManager = weakContext?.getSystemService(Context.LOCATION_SERVICE) as LocationManager
locationManager.isLocationEnabled
}
Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT -> {
// This is Deprecated in API 28
val mode = Settings.Secure.getInt(
weakContext?.contentResolver, Settings.Secure.LOCATION_MODE,
Settings.Secure.LOCATION_MODE_OFF
)
mode != Settings.Secure.LOCATION_MODE_OFF
}
else -> {
val locationProviders = Settings.Secure.getString(weakContext?.contentResolver, Settings.Secure.LOCATION_PROVIDERS_ALLOWED)
return !TextUtils.isEmpty(locationProviders)
}
}
}
@SuppressLint("MissingPermission")
fun getCurrentLocation(
weakContext: WeakReference<Context>,
success: (String?) -> Unit,
error: () -> Unit
) {
if (isLocationEnabled(weakContext.get())) {
weakContext.get()
?.let { context ->
fusedLocationClient = LocationServices.getFusedLocationProviderClient(context)
fusedLocationClient.lastLocation.addOnSuccessListener { location ->
getCurrentCity(context, location, success)
}
}
} else {
error()
}
}
private fun getCurrentCity(
context: Context,
location: Location?,
success: (String?) -> Unit
) {
val city = try {
location?.let {
val geocoder = Geocoder(context, Locale.getDefault())
val address = geocoder.getFromLocation(it.latitude, it.longitude, 1)
address[0].locality
}
} catch (e: Exception) {
"Bangalore"
}
success(city)
}
}
【问题讨论】:
-
你有什么发现吗?我也有类似的问题。
-
到目前为止,我在我的活动中使用它。但仍在寻找推荐的解决方案。
标签: android android-mvvm