wake-up-neo.com

So überprüfen Sie die Berechtigungen von Grant-Berechtigungen zur Laufzeit

In Android M (Vorschau) kann der Benutzer eine bestimmte App auswählen und bestimmte Berechtigungen abrufen.

Ich frage also Wie prüfe ich die Berechtigungen für die Erteilung von Zuschüssen zur Laufzeit?

37
Chulo

Nett !!

Ich habe gerade mein Bedürfnis gefunden, dass wir prüfen können, ob die Erlaubnis erteilt wird durch:

checkSelfPermission(Manifest.permission.READ_CONTACTS)

Fordern Sie ggf. Berechtigungen an

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;
    }

Behandeln Sie die Antwort auf die Berechtigungsanforderung

@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
    }
}
49
Chulo

Versuchen Sie stattdessen den einfachen Anforderungscode
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;
}
33
Venkatesh

Versuchen Sie Folgendes für die Überprüfung der Laufzeitberechtigung: 

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    checkRunTimePermission();
}

Laufzeitberechtigung prüfen:

private void checkRunTimePermission() {
    String[] permissionArrays = new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        requestPermissions(permissionArrays, 11111);
    } else {
         // if already permition granted
        // PUT YOUR ACTION (Like Open cemara etc..)
    }
}

Handle Permission-Ergebnis:

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    boolean openActivityOnce = true;
    boolean openDialogOnce = true;
    if (requestCode == 11111) {
        for (int i = 0; i < grantResults.length; i++) {
            String permission = permissions[i];

            isPermitted = grantResults[i] == PackageManager.PERMISSION_GRANTED;

            if (grantResults[i] == PackageManager.PERMISSION_DENIED) {
                // user rejected the permission
                boolean showRationale = shouldShowRequestPermissionRationale(permission);
                if (!showRationale) {
                    //execute when 'never Ask Again' tick and permission dialog not show
                } else {
                    if (openDialogOnce) {
                        alertView();
                    }
                }
            }
        }

        if (isPermitted)
            if (isPermissionFromGallery)
                openGalleryFragment();
    }
}

Benutzerdefinierte Benachrichtigung einstellen:

private void alertView() {
    AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity(), R.style.MyAlertDialogStyle);

    dialog.setTitle("Permission Denied")
            .setInverseBackgroundForced(true)
            //.setIcon(R.drawable.ic_info_black_24dp)
            .setMessage("Without those permission the app is unable to save your profile. App needs to save profile image in your external storage and also need to get profile image from camera or external storage.Are you sure you want to deny this permission?")

            .setNegativeButton("I'M SURE", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialoginterface, int i) {
                    dialoginterface.dismiss();
                }
            })
            .setPositiveButton("RE-TRY", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialoginterface, int i) {
                    dialoginterface.dismiss();
                    checkRunTimePermission();

                }
            }).show();
}
7
fun hasPermission(permission: String): Boolean {
      if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) return true // must be granted after installed.
      return mAppSet.appContext.checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED
}
3
Jacks Gong

Die beste Beschreibung ist am: http://inthecheesefactory.com/blog/things-you-need-to-know-about-Android-m-permission-developer-edition/de

Für einfache Benutzungsberechtigungen können Sie diese Bibliothek verwenden: http://hotchemi.github.io/PermissionsDispatcher/

2
mtrakal

benutze Dexter Bibliothek

Binden Sie die Bibliothek in Ihren build.gradle ein

dependencies{
    implementation 'com.karumi:dexter:4.2.0'
}

dieses Beispiel fordert WRITE_EXTERNAL_STORAGE. an

Dexter.withActivity(this)
                .withPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .withListener(new PermissionListener() {
                    @Override
                    public void onPermissionGranted(PermissionGrantedResponse response) {
                        // permission is granted, open the camera
                    }

                    @Override
                    public void onPermissionDenied(PermissionDeniedResponse response) {
                        // check for permanent denial of permission
                        if (response.isPermanentlyDenied()) {
                            // navigate user to app settings
                        }
                    }

                    @Override
                    public void onPermissionRationaleShouldBeShown(PermissionRequest permission, PermissionToken token) {
                        token.continuePermissionRequest();
                    }
                }).check();

überprüfe diese Antwort hier

1
AL Tegani

Für die Berechtigung zur Standortlaufzeit 

ActivityCompat.requestPermissions(this,new String[]{Android.Manifest.permission.ACCESS_FINE_LOCATION}, 1);

public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {
        case 1: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Log.d("yes","yes");

            } else {
                Log.d("yes","no");
                // permission denied, boo! Disable the
                // functionality that depends on this permission.
            }
            return;
        }
        // other 'case' lines to check for other
        // permissions this app might request
    }
}
1
Makvin

original (nicht meiner) post hier

Für spezielle Berechtigungen wie Android.Manifest.permission.PACKAGE_USAGE_STATS wird AppOpsManager verwendet: 
Kotlin

private fun hasPermission(permission:String, permissionAppOpsManager:String): Boolean {
    var granted = false
    if (VERSION.SDK_INT >= VERSION_CODES.M) {
        // requires KitKat
        val appOps = applicationContext!!.getSystemService(Context.APP_OPS_SERVICE) as AppOpsManager

        // requires Lollipop
        val mode = appOps.checkOpNoThrow(permissionAppOpsManager,
                              Android.os.Process.myUid(), applicationContext!!.packageName)

        if (mode == AppOpsManager.MODE_DEFAULT) {
            granted = applicationContext!!.checkCallingOrSelfPermission(permission) == PackageManager.PERMISSION_GRANTED
        } else {
            granted = mode == AppOpsManager.MODE_ALLOWED
        }
    }

    return granted
}

und überall im Code: 

val permissionAppOpsManager = AppOpsManager.OPSTR_GET_USAGE_STATS
val permission = Android.Manifest.permission.PACKAGE_USAGE_STATS
val permissionActivity = Settings.ACTION_USAGE_ACCESS_SETTINGS

if (hasPermission(permission, permissionAppOpsManager)) {
    Timber.i("has permission: $permission")
    // do here what needs permission
} else {
    Timber.e("has no permission: $permission")
    // start activity to get permission
    startActivity(Intent(permissionActivity))
}

Andere Berechtigungen erhalten Sie mit TedPermission-Bibliothek

0
Evgenii Vorobei

Sie können auch abfragen, indem Sie dem Codeausschnitt als abwärtskompatibel folgen.

int hasPermission = ContextCompat.checkSelfPermission(this,Manifest.permission.WRITE_CONTACTS);
if (hasPermission == PackageManager.PERMISSION_GRANTED) {
    //Do smthng
}
0
DiRiNoiD