如何使用新架构组件跟踪 android 中的当前位置?

How to track current location in android with new architecture components?

我有一个项目,我在其中成功实现了位置跟踪功能,并且运行良好。我每 30 秒使用融合位置提供程序跟踪用户当前位置。(跟踪在 MainActivity 启动时开始)。

现在我计划用新引入的 android 架构组件更新该项目。但我不知道如何使用视图实现位置跟踪 model.Where 是开始位置跟踪的正确位置,在 MainActivity 或 Application class 中?我应该使用 ViewModel 还是 AndroidViewModel?如何实现。

正确的方法是 TrackingRepository 在设备位置的后台线程中进行所有计算。创建一个 MutableLiveData,您将在其中分配位置。然后使用 postValue()setValue() 更新其值。为这个MutableLiveData写一个publicgetter。此存储库将是您的位置 API。

然后您的 ViewModel 应该调用存储库的方法并将其结果分配给 ViewModelLiveData 变量。然后在你的 Fragment/Activity 中观察你的 ViewModel 的 liveData。正如 Guide to App Architecture 所做的那样。

记得使用依赖注入,这对新架构很有帮助。

经过几个小时的尝试,终于找到了解决办法。

首先在 LocationRepository 中创建一个变量。

val currentLocation = MutableLiveData<Location>()

在 LocationCallBack (onLocationResult) 内部

currentLocation.postValue(locationResult.lastLocation)

此后在 ViewModel 中再次 class

val currentLocation = MutableLiveData<Location>()

fun currentLocation(): MutableLiveData<Location>
{
    currentLocation = myLocationProvider.currentLocation
    return currentLocation
}

至少你在 Activity/Fragment

中观察到了 ViewModel 的 MutableLiveDate
myLocationProvider.currentLocation.observe(this, Observer { currentLocation ->
            currentLocation?.let {
                //Your code here
            }
})

编辑 您必须使用 suspendCoroutine、GlobalScope 和 UiDispatcher 启动 LocationCallback。