如何在Android的运行时请求权限? [英] How i can request permission at runtime in Android?

查看:95
本文介绍了如何在Android的运行时请求权限?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个Android应用程序,必须允许用户使用相机扫描QRCode.

I'm developing an Android application, I have to allow users to use camera to scan a QRCode.

在每个Android版本中(> 6.0除外),我都没问题,但是在棉花糖中,我必须手动启用设置->应用程序->许可"中的许可 (这很奇怪,因为我已在清单中声明了摄像头许可).

In each Android version (except > 6.0) i haven't problem, but in marshmallow I must enable manually the permission from "Settings -> App ->Permission" (it's strange because I have declared the camera permission in the manifest).

我阅读了文档dev-android网站,但我不了解某些内容:

I read the documentation dev-android website but i don't understand some things:

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

    }
}

第二部分代码:

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

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

How i can adapt this code to my problem ?

什么是"MY_PERMISSIONS_REQUEST_READ_CONTACTS"?

What is "MY_PERMISSIONS_REQUEST_READ_CONTACTS" ?

推荐答案

MY_PERMISSIONS_REQUEST_READ_CONTACTS是一个静态int变量,您需要在Activity中进行设置.它是onRequestPermissionsResult中使用的请求代码.这是必需的,以便您了解onRequestPermissionsResult中对哪个权限进行了操作(是接受还是拒绝).

MY_PERMISSIONS_REQUEST_READ_CONTACTS is a static int variable that you need to set in your Activity. It is the request code that is used in onRequestPermissionsResult. It is required so that you know which permission was acted upon (whether it be accepted or rejected) in onRequestPermissionsResult.

在活动"的顶部,只需输入private static final int MY_PERMISSIONS_REQUEST_READ_CONTACTS = 1;(数字可以是您想要的任何数字)

At the top of your Activity just put private static final int MY_PERMISSIONS_REQUEST_READ_CONTACTS = 1; (the number can be whatever you want)

这篇关于如何在Android的运行时请求权限?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆