【发布时间】:2021-08-08 18:24:59
【问题描述】:
所以我有一个包含多个片段的应用程序。每次用户导航到新片段时,我都想存储设备位置。所有片段都位于一个 Activity 下。
这是我现在正在做的事情:
在我的活动中:
fun getLocation(context: Context, consumer: Consumer<Location?>): Boolean {
return if (checkLocationPermission()) {
mService.getLocation(context, consumer)
} else {
false
}
}
在我的 LocationService 中(locationService 绑定到我的活动)
@RequiresPermission(value = "android.permission.ACCESS_FINE_LOCATION")
fun getLocation(context: Context, consumer: Consumer<Location?>): Boolean {
return if (packageManager.hasSystemFeature(PackageManager.FEATURE_LOCATION)
&& manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
manager.getCurrentLocation(
LocationManager.GPS_PROVIDER,
null,
ContextCompat.getMainExecutor(context),
consumer)
true
} else {
false
}
}
最后,这是我在 Fragment 中请求位置的方式。 在我的片段中:
val a = requireActivity() as MyActivity
a.getLocation(a) { loc ->
// this callback always takes about 30 seconds to execute, and then loc is null
}
我正在我的 Pixel 3a 手机上对此进行测试。我在室内,所以我不知道这是否会影响 GPS,但它至少能够在谷歌地图中显示我的位置。
我还尝试在模拟器 (Pixel 2 API 30) 上对此进行测试,并且 确实 返回了一个位置,但即使我更改设备,它也始终是默认位置 (Palo Alto Googleplex)模拟器设置中的位置。
【问题讨论】:
标签: android kotlin locationmanager