Reputation: 1322
I'm making an Android App that adds a map to a activity, the user can center the map with their current location using the "location layer". to add the location button in the map with:
mMap.isMyLocationEnabled = true
I'm checking for the ACCESS_FINE_LOCATION
permission inside onMapReady
method and everything works fine, but I need finish the activiy and re-open it to see the changes (the location button).
So, I'm using onRequestPermissionsResult
to check the user response, but when I call mMap.isMyLocationEnabled = true
Android Studio says:
Call requires permisson which may be rejected by user: code shoud explicitly check to see if permission is available (with checkPermission) or explicitly handle a potencial SecurityException...
This is my code:
override fun onMapReady(googleMap: GoogleMap) {
mMap = googleMap
mMap.uiSettings.isCompassEnabled = true
if(ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this, arrayOf(android.Manifest.permission.ACCESS_FINE_LOCATION),SOLICITA_UBICACION_CLAVE)
}else{
mMap.isMyLocationEnabled = true
}
mMap.uiSettings.isMyLocationButtonEnabled = true
mMap.uiSettings.isZoomControlsEnabled = true
// Add a marker in Sydney and move the camera
val sydney = LatLng(-34.0, 151.0)
mMap.addMarker(MarkerOptions().position(sydney).title("Marker in Sydney"))
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney))
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when(item.itemId){
android.R.id.home -> {
onBackPressed()
return true
}
}
return super.onOptionsItemSelected(item)
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
when(requestCode){
SOLICITA_UBICACION_CLAVE -> {
if((grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED)){
mMap.isMyLocationEnabled = true
Toast.makeText(this@MapsActivity,"Permiso garantizado",Toast.LENGTH_SHORT).show()
}else{
mMap.isMyLocationEnabled = false
Toast.makeText(this@MapsActivity,"Permiso denegado",Toast.LENGTH_SHORT).show()
}
}
}
}
So, How can I call mMap.isMyLocationEnabled = true
inside onRequestPermissionsResult
?,
What's the purpose to check a permission inside when
instruction for the request code if is supposed that is currently granted?
Upvotes: 0
Views: 447
Reputation: 1006674
So, How can I call mMap.isMyLocationEnabled = true inside onRequestPermissionsResult?,
Do it the way that you are, and add the appropriate @SuppressLint
annotation to suppress the warning. There should be a quick-fix for this in Android Studio that will add@SuppressLint
with the right property.
Presumably, there is some bug or limitation in the Lint rule that is causing your problem. For example, this is a relatively old Lint check, and so perhaps it is not handling all Kotlin scenarios correctly.
Upvotes: 1