我如何在运行时在 Android 中请求权限?

2 permissions android android-manifest

我正在开发一个 Android 应用程序,我必须允许用户使用相机扫描二维码。

在每个 Android 版本(> 6.0 除外)中,我都没有问题,但在棉花糖中,我必须手动启用“设置 - > 应用 - > 权限”中的权限(这很奇怪,因为我已经在清单中声明了相机权限)。

我阅读了文档 dev-android 网站,但我不明白一些事情:

if (ContextCompat.checkSelfPermission(thisActivity,
                Manifest.permission.READ_CONTACTS)
        != PackageManager.PERMISSION_GRANTED) {

    if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
            Manifest.permission.READ_CONTACTS)) {

        } else {    
        ActivityCompat.requestPermissions(thisActivity,
                new String[]{Manifest.permission.READ_CONTACTS},
                MY_PERMISSIONS_REQUEST_READ_CONTACTS);

    }
}
Run Code Online (Sandbox Code Playgroud)

代码的第二部分:

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

                // permission was granted, yay! Do the
                // contacts-related task you need to do.

            } else {

                // permission denied, boo! Disable the
                // functionality that depends on this permission.
            }
            return;
        }

        // other 'case' lines to check for other
        // permissions this app might request
    }
}
Run Code Online (Sandbox Code Playgroud)

我如何使此代码适应我的问题?

什么是“MY_PERMISSIONS_REQUEST_READ_CONTACTS”?

Ric*_*ins 5

MY_PERMISSIONS_REQUEST_READ_CONTACTS 是您需要在活动中设置的静态 int 变量。它是 中使用的请求代码onRequestPermissionsResult。它是必需的,以便您知道在onRequestPermissionsResult.

在您的活动顶部放置private static final int MY_PERMISSIONS_REQUEST_READ_CONTACTS = 1;(数字可以是任何您想要的)


Khe*_*raj 5

RxPermission现在是广泛使用的库。如果编写所有代码以获得许可,它会变得复杂。

RxPermissions rxPermissions = new RxPermissions(this); // where this is an Activity instance // Must be done during an initialization phase like onCreate
rxPermissions
    .request(Manifest.permission.CAMERA)
    .subscribe(granted -> {
        if (granted) { // Always true pre-M
           // I can control the camera now
        } else {
           // Oups permission denied
        }
    });
Run Code Online (Sandbox Code Playgroud)

您的 build.gradle

allprojects {
    repositories {
        ...
        maven { url 'https://jitpack.io' }
    }
}

dependencies {
    implementation 'com.github.tbruyelle:rxpermissions:0.10.1'
    implementation 'com.jakewharton.rxbinding2:rxbinding:2.1.1'
}
Run Code Online (Sandbox Code Playgroud)

这不是很容易吗?