2

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

现在我打算用新引入的 android 架构组件来更新那个项目。但我不知道如何使用视图模型实现位置跟踪。在MainActivity 或 Application类中开始位置跟踪的正确位置在哪里?我应该使用ViewModel 还是 AndroidViewModel?如何实现这一点。

4

2 回答 2

4

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

然后您ViewModel应该调用存储库的方法并将其结果分配LiveDataViewModel. 然后在您的片段/活动中观察您的ViewModel. 正如应用架构指南所做的那样。

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

于 2017-12-06T14:13:06.627 回答
2

经过几个小时的尝试,我终于找到了解决方案。

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

val currentLocation = MutableLiveData<Location>()

LocationCallBack (onLocationResult) 内部

currentLocation.postValue(locationResult.lastLocation)

此后再次在 ViewModel 类中

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。

于 2019-06-15T13:44:15.000 回答