You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android中LocationCallback的onLocationResult方法报错解决咨询

问题解决方法

核心原因

你遇到的冲突是因为Google Play Services Location库的版本差异导致LocationCallback中onLocationResult方法的参数可空性发生了变化:

  • 旧版本库中,该方法的参数是可空的LocationResult?
  • 新版本(18.0.0+)中,Google给参数加上了@NonNull注解,Kotlin会识别为非空的LocationResult

你的代码签名和当前依赖的库版本不匹配,才会出现两种报错。

具体解决步骤

  1. 确认并升级依赖版本
    打开你的模块级build.gradle(或build.gradle.kts),确保使用最新稳定版的定位库:
// 最新稳定版以Google官方为准,当前示例为21.0.1
implementation 'com.google.android.gms:play-services-location:21.0.1'

同步项目后,修改locationCallback的代码:

private val locationCallback = object : LocationCallback() {
    override fun onLocationResult(locationResult: LocationResult) {
        // lastLocation仍然可能为空,保留空安全处理
        locationResult.lastLocation?.let { location ->
            val newLocation = LatLng(location.latitude, location.longitude)
            updateMarkerPosition(newLocation)
        }
    }
}
  1. 如果必须使用旧版本库
    若因项目限制无法升级,将参数改为可空,并确保方法签名和父类完全一致:
private val locationCallback = object : LocationCallback() {
    override fun onLocationResult(locationResult: LocationResult?) {
        locationResult?.lastLocation?.let { location ->
            val newLocation = LatLng(location.latitude, location.longitude)
            updateMarkerPosition(newLocation)
        }
    }
}

若仍报错,可尝试清理项目缓存(File -> Invalidate Caches...)后重新同步。

报错解释

  • 未加override时:Kotlin会自动为非空参数生成JVM兼容签名,和你自己写的可空参数方法在JVM层面签名重复,触发"Accidental override"。
  • 加override时:当前依赖的库中onLocationResult的参数是非空的,你写的可空参数方法找不到对应的父类方法,所以提示"'onLocationResult' overrides nothing"。

内容的提问来源于stack exchange,提问作者Daniel Lip

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 13:33:31