无法使用给定参数调用 requestLocationUpdates

Can not call requestLocationUpdates with given arguments

private var locationManager: LocationManager? = null

/*onCreate()*/
locationManager = requireActivity()
        .getSystemService(LOCATION_SERVICE) as LocationManager

/*Listener is declared as */
private val locationListener = LocationListener {
     ...
}

 /*Then on button click I want to request location update and hope to see update in my listener*/
 locationManager?.requestLocationUpdates(
        "dsa",
        0.toLong(),
        0.toFloat(),
        locationListener!!
    )

我想测试 requestLocationUpdates,但它说函数不支持给定的参数。奇怪,因为 requestLocationUpdates 具有 String、Long、Float、LocationListener 属性。什么会导致这个?我做错了什么吗?

根据文档here

如果提供程序为空或此设备上不存在,将抛出 IllegalArgumentException 我认为您的设备中可能不存在“dsa”提供程序。您应该使用 LocationManager.NETWORK_PROVIDERLocationManager.PASSIVE_PROVIDERLocationManager.GPS_PROVIDER

您的代码错误应该不止一处。原因是 LocationListener 是一个 interface 而您将其视为其他东西。要解决此问题,请将 LocationListener 代码更改为以下代码段。

public val locationListener = object: LocationListener{ ... }

记得覆盖所有必要的 methods.Also 删除非空断言 !!,没有必要这样做。该错误现在应该消失了。