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

Kotlin开发Android应用GPS位置更新报onLocationResult覆写错误

错误原因

'onLocationResult' overrides nothing 报错的核心原因是你依赖的新版Google定位服务SDK中,LocationCallback的onLocationResult方法入参LocationResult为非空类型,你写的方法签名里加了可空标记?,和父类方法定义不匹配,编译器判定你没有正确重写父类方法。
除此之外你没法拿到持续定位更新还有两个关键遗漏:

  • 你只初始化了locationRequest和locationCallback,从未调用requestLocationUpdates方法向系统注册位置更新监听,自然只会拿到一次lastLocation的返回结果
  • 你注释掉了定位优先级配置,默认低优先级模式下定位更新频率会极低甚至不返回更新,同时你在权限申请通过后没有触发定位启动逻辑
修复方案

按以下步骤调整即可:

  1. 修正onLocationResult的方法签名,去掉入参后的可空标记?,和SDK方法定义对齐
  2. 抽离单独的定位启动方法,在权限校验通过、页面回到可见状态时调用requestLocationUpdates注册持续定位监听
  3. 打开高精度定位配置,保证定位更新正常触发
  4. 在页面不可见时移除定位监听,避免不必要的耗电和内存泄漏
  5. 补全权限申请结果的回调逻辑,用户授权后立刻启动定位
完整可运行参考代码
class MainActivity : AppCompatActivity() {
    private lateinit var fusedLocationClient: FusedLocationProviderClient
    private lateinit var locationRequest: LocationRequest
    private lateinit var locationCallback: LocationCallback
    private val LOCATION_PERMISSION_REQ = 101

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)

        // 配置定位请求参数
        locationRequest = LocationRequest.create().apply {
            interval = 10000
            fastestInterval = 5000
            priority = LocationRequest.PRIORITY_HIGH_ACCURACY
        }

        // 正确重写定位回调,注意入参不要加?
        locationCallback = object : LocationCallback() {
            override fun onLocationResult(locationResult: LocationResult) {
                for (location in locationResult.locations) {
                    updateLocationDisplay(location)
                }
            }
        }

        gpsPermissionCheck()
    }

    override fun onStart() {
        super.onStart()
        // 页面可见且有权限时启动定位
        if (hasLocationPermission()) startLocationUpdates()
    }

    override fun onStop() {
        super.onStop()
        // 页面不可见时停止定位
        fusedLocationClient.removeLocationUpdates(locationCallback)
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == LOCATION_PERMISSION_REQ) {
            if (grantResults.firstOrNull() == PackageManager.PERMISSION_GRANTED) {
                startLocationUpdates()
            } else {
                Toast.makeText(this, "需要定位权限才能获取位置信息", Toast.LENGTH_SHORT).show()
            }
        }
    }

    @SuppressLint("MissingPermission")
    private fun startLocationUpdates() {
        // 先获取最后一次已知位置快速展示
        fusedLocationClient.lastLocation.addOnSuccessListener { loc ->
            loc?.let { updateLocationDisplay(it) }
        }
        // 注册持续定位监听,这步是原有代码缺失的核心逻辑
        fusedLocationClient.requestLocationUpdates(
            locationRequest,
            locationCallback,
            Looper.getMainLooper()
        )
    }

    private fun updateLocationDisplay(location: Location) {
        val displayText = "纬度: ${location.latitude}   经度: ${location.longitude}"
        val label = findViewById<TextView>(resources.getIdentifier("txtlabel", "id", packageName))
        label.text = displayText
        println("定位更新: $displayText")
    }

    private fun gpsPermissionCheck() {
        if (!hasLocationPermission()) {
            ActivityCompat.requestPermissions(
                this,
                arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
                LOCATION_PERMISSION_REQ
            )
        }
    }

    private fun hasLocationPermission(): Boolean {
        return ContextCompat.checkSelfPermission(
            this,
            Manifest.permission.ACCESS_FINE_LOCATION
        ) == PackageManager.PERMISSION_GRANTED
    }
}

补充说明:需要在AndroidManifest.xml中声明定位权限,否则权限校验永远不通过:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

如果后续遇到方法签名报错,直接将光标放在报错的重写方法上,通过IDE的自动补全生成正确签名即可,不需要手动硬写方法定义。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 14:48:19