代码之家  ›  专栏  ›  技术社区  ›  sagar suri

android mvvm架构中使用位置api的合适位置

  •  0
  • sagar suri  · 技术社区  · 7 年前

    我有一个场景,我想向用户显示当前的天气数据,我正在获取他/她当前的lat/lng,并对其进行反向地理编码以获取城市名称。一旦我有了城市的名字,我会打一个网络电话,并显示天气数据。除此之外,我还需要执行许多定位操作。

    所以我创建了一个名为 LocationUtils.kt .我遵循MVVM架构,想知道哪一层是调用 LocationUtils 方法,是吗 view 层还是层 viewmodel 层还是层 data 层自从 FusedLocationProvider 需要 context 如果我用在 ViewModel 它会漏的。那么如何解决这个问题呢?

    地点。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)
      }
    }
    
    0 回复  |  直到 7 年前
        1
  •  2
  •   Abdul Mateen    7 年前

    我也在研究同样的问题。我还必须处理使用MVVM架构向用户显示天气数据的问题。此刻,我和你们现在处在同一个点上。解决方案似乎是所谓的“依赖注入(DI)”。基本上,我们可以注入依赖项,比如 Context 给我们 ViewModel 使用“匕首2”等工具/框架。DI的耦合比直接通过低 上下文 到 视图模型 并能更好地符合MVVM的要求。那么,它的实际位置呢 FusedLocationProvider IMO将在ViewModel中,但在实施DI之后。也许其他人可以更详细地解释我的解释。一旦我自己实现依赖注入,我将更新我的答案。

        2
  •  -1
  •   Waldmann AphexMunky    6 年前

    我把它放在我的ViewModel中。 为了通过 context 作为你的论点 ViewModel 你可以延长 AndroidViewModel 而不是 视图模型 .例如:

    class CurrentViewModel(application: Application) : AndroidViewModel(application) {
        val context = application
        val locationResolver = LocationResolver(context)//this one converts latitude and longitude into City name of type String
    
    
    fun detectCity() {
            Log.d(LocationResolver.TAG, "entered detectLocation()")
            val fusedLocationClient = LocationServices.getFusedLocationProviderClient(context)
            fusedLocationClient.lastLocation
                .addOnSuccessListener { location ->
                    if (location != null) {
                        Repository._currentName.value = locationResolver.getLocationFromCoordinates(
                            location.latitude,
                            location.longitude
                        )
                        Log.d(
                            LocationResolver.TAG,
                            "New city name is:" + Repository.currentLocationCity
                        )
                    }
    
                }
        }
    
    

    然后你可以通过 DataBinding .