Android中如何获取Geofence触发坐标而无需重新发起GPS定位请求
地理围栏触发坐标获取方案
GeofencingEvent 实例本身已内置系统触发围栏事件时采集的定位信息,无需额外发起GPS定位请求即可直接获取你需要的x2、y2坐标:
你可以调用geofencingEvent.triggeringLocation属性获取触发事件的Location对象,从该对象中即可提取经纬度坐标。
修改后可运行的参考代码
class GeofenceLocationReceiver: BroadcastReceiver() { [...] override fun onReceive(context: Context?, intent: Intent?) { val geofencingEvent = GeofencingEvent.fromIntent(intent) if (geofencingEvent.hasError()) { val errorMessage = GeofenceStatusCodes.getStatusCodeString(geofencingEvent.errorCode) Log.e(Category.LOCATION, "GEOFENCE result has errors: $errorMessage") return } if (geofencingEvent.geofenceTransition == Geofence.GEOFENCE_TRANSITION_ENTER || geofencingEvent.geofenceTransition == Geofence.GEOFENCE_TRANSITION_EXIT) { // 直接获取触发围栏穿越时的坐标,无需额外请求GPS val triggerLocation = geofencingEvent.triggeringLocation triggerLocation?.let { location -> val x2 = location.latitude val y2 = location.longitude // 此处可直接使用x2、y2进行业务逻辑处理 Log.d(Category.LOCATION, "围栏触发坐标:纬度=$x2,经度=$y2") } ?: run { Log.e(Category.LOCATION, "触发位置为空,无法获取坐标") } geofencingEvent.triggeringGeofences.firstOrNull()?.let { val geofenceId = it.requestId // 原有围栏相关业务逻辑 } } else { Log.e(Category.LOCATION, "INVALID TYPE") } } }
补充说明
triggeringLocation返回的Location对象除经纬度外,还可获取定位精度、触发时间戳、移动速度等附加信息- 该定位是系统触发围栏事件时的原始采集结果,和主动发起定位请求拿到的返回值格式完全一致,无需额外转换
- 极端场景下
triggeringLocation可能返回空值,建议增加空校验避免崩溃
内容的提问来源于stack exchange,提问作者kosiara - Bartosz Kosarzycki
相关产品推荐
相关产品推荐

