我了解您需要在fusedLocationProviderClient
上执行方法之前检查用户是否已允许位置。所以我创建了一个像这样的全局方法:
fun locationAllowed(context: Context): Int {
if (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED){
return PackageManager.PERMISSION_GRANTED
}
return PackageManager.PERMISSION_DENIED
}
并在我的活动中使用了它:
class Home : FragmentActivity() {
lateinit var fusedLocationProviderClient: FusedLocationProviderClient
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_home)
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this)
if (locationAllowed(this) == PackageManager.PERMISSION_GRANTED) {
fusedLocationProviderClient.lastLocation // still gives me the error
}
}
}
但是我在fusedLocationProviderClient.lastLocation
上仍然有红色下划线:Call requires permission which may be rejected by user: code should explicitly check to see if permission is available (with checkPermission) or explicitly handle a potential SecurityException.
知道为什么吗?