我了解您需要检查用户是否允许位置,然后再对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.
知道为什么吗?