[英]How to track current location in android with new architecture components?
I have a project, in which I have successfully implemented location tracking feature, and is working perfectly. 我有一个项目,已在其中成功实现了位置跟踪功能,并且运行良好。 I am tracking users current location using fused location provider in every 30 seconds.(tracking starts when MainActivity started).
我每30秒钟使用融合的位置提供程序跟踪用户的当前位置。(跟踪从MainActivity启动时开始)。
Now I am planning to update that project with newly introduced android architecture components. 现在,我计划使用新引入的android体系结构组件来更新该项目。 But I don't know how to implement location tracking with view model.Where is the right place to start location tracking, in MainActivity or Application class?
但是我不知道如何使用视图模型实现位置跟踪.MainActivity或Application类中在哪里开始位置跟踪? Should I use ViewModel or AndroidViewModel ?
我应该使用ViewModel还是AndroidViewModel ? How to achieve this.
如何实现这一目标。
The correct way would be to have a TrackingRepository
where you do all calculations in a background thread of the device location. 正确的方法是拥有一个
TrackingRepository
,在其中您可以在设备位置的后台线程中进行所有计算。 Create a MutableLiveData
where you will assign the location. 创建一个
MutableLiveData
,您将在其中分配位置。 Then update its value using postValue()
or setValue()
. 然后使用
postValue()
或setValue()
更新其值。 Write a public getter for this MutableLiveData
. 为此
MutableLiveData
编写一个公共获取MutableLiveData
。 This repository will be your location API. 该存储库将是您的位置API。
Then your ViewModel
should call the method of your repository and assign its result to a LiveData
variable of the ViewModel
. 然后,您的
ViewModel
应该调用存储库的方法,并将其结果分配给ViewModel
的LiveData
变量。 Then in your Fragment/Activity observe the liveData of your ViewModel
. 然后在Fragment / Activity中观察
ViewModel
的liveData。 Just as the Guide to App Architecture does. 就像App Architecture指南一样。
Remember to use dependency injection which really helps with the new architecture. 记住要使用依赖注入,它对新架构确实有帮助。
After few hours of try, finally I could find the solution. 经过几个小时的尝试,终于可以找到解决方案。
First create a variable inside the LocationRepository. 首先在LocationRepository内部创建一个变量。
val currentLocation = MutableLiveData<Location>()
Inside the LocationCallBack (onLocationResult) 在LocationCallBack内部(onLocationResult)
currentLocation.postValue(locationResult.lastLocation)
Thereafter in the ViewModel class again 之后,再次在ViewModel类中
val currentLocation = MutableLiveData<Location>()
and 和
fun currentLocation(): MutableLiveData<Location>
{
currentLocation = myLocationProvider.currentLocation
return currentLocation
}
at least you have observe the ViewModel's MutableLiveDate in your Activity/Fragment 至少您在Activity / Fragment中观察到了ViewModel的MutableLiveDate
myLocationProvider.currentLocation.observe(this, Observer { currentLocation ->
currentLocation?.let {
//Your code here
}
})
EDIT You have to start the the LocationCallback with suspendCoroutine, GlobalScope and UiDispatcher. 编辑您必须使用suspendCoroutine,GlobalScope和UiDispatcher启动LocationCallback。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.