¿Cómo comprobar los permisos de concesión en tiempo de ejecución?
En Android M (Vista previa), el usuario puede elegir una aplicación específica y recuperar un permiso específico.
Entonces pregunto ¿Cómo verificar los permisos de concesión en tiempo de ejecución ?
Aceptado
Puede utilizar el siguiente código copiado de https://android.googlesource.com/platform/frameworks/base/+blame/71c2c37554ae53dffdf8e210f484d92af30620fa/docs/html/preview/features/runtime-permissions.jd?pli=1#548 —
Solicitar permisos si es necesario
if (checkSelfPermission(Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) { requestPermissions(new String[]{Manifest.permission.READ_CONTACTS}, MY_PERMISSIONS_REQUEST_READ_CONTACTS); // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an // app-defined int constant return; }
Manejar la respuesta de solicitud de permisos
@Override public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { switch (requestCode) { case MY_PERMISSIONS_REQUEST_READ_CONTACTS: { if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { // permission was granted, yay! do the // calendar task you need to do. } else { // permission denied, boo! Disable the // functionality that depends on this permission. } return; } // other 'switch' lines to check for other // permissions this app might request } }
Pruebe este código de solicitud simple
https://www.learn2crack.com/2015/10/android-marshmallow-permissions.html
public static final int REQUEST_ID_MULTIPLE_PERMISSIONS = 1;
private boolean checkAndRequestPermissions() {
int camera = ContextCompat.checkSelfPermission(this, android.Manifest.permission.CAMERA);
int storage = ContextCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
int loc = ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION);
int loc2 = ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION);
List<String> listPermissionsNeeded = new ArrayList<>();
if (camera != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(android.Manifest.permission.CAMERA);
}
if (storage != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
}
if (loc2 != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(android.Manifest.permission.ACCESS_FINE_LOCATION);
}
if (loc != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(android.Manifest.permission.ACCESS_COARSE_LOCATION);
}
if (!listPermissionsNeeded.isEmpty())
{
ActivityCompat.requestPermissions(this,listPermissionsNeeded.toArray
(new String[listPermissionsNeeded.size()]),REQUEST_ID_MULTIPLE_PERMISSIONS);
return false;
}
return true;
}