【问题标题】:Use same GPS location code on multiple fragments在多个片段上使用相同的 GPS 位置代码
【发布时间】:2022-07-19 17:47:58
【问题描述】:
我想制作一个包含五个不同片段的应用程序。在每个片段中,我都需要设备的 GPS 位置,但目的会有所不同。
为了不为每个片段实现五次 FusedLocationProviderClient,我想在 MainActivity 中执行一次并将结果发送到显示的片段。
作为java编程的初学者,我请求你指导。如何确定设备的 GPS 位置并自动将位置发送(在每次更新时)到活动片段?
也许是服务之类的东西?欢迎任何示例代码。提前致谢!
【问题讨论】:
标签:
java
android
android-studio
android-fragments
location
【解决方案1】:
使用ViewModel 有一个简单的解决方案。
这个概念是您初始化一个状态持有者并在您的片段之间共享该持有者的相同实例。
该持有者的实例存储在您的活动中。
您的 ViewModel 可能如下所示
public class MyViewModel extends ViewModel {
private MutableLiveData<LatLng> location;
public LiveData<LatLng> getLocation() {
if (location == null) {
location = new MutableLiveData<LatLng>();
}
return location;
}
private void setLocation(LatLng value) {
if (location == null) {
location.setValue(value)
}
}
}
在您的活动中获取此视图模型的实例。我们为此使用工厂。
private MyViewModel model;
//in your activity onCreate
model = new ViewModelProvider(this).get(MyViewModel.class);
//and from location callback
model.setLocation(latlng)
在您的所有片段中,您都可以观察到这些数据
//first get the same instance of your ViewModel onViewCreated
model = new ViewModelProvider(requireActivity()).get(SharedViewModel.class);
model.getLocation().observe(getViewLifecycleOwner(), item -> {
// Update the UI.
//will execture everytime new data is set
});