什么时候在运行时为Android Marshmallow 6.0请求权限? [英] When to request permission at runtime for Android Marshmallow 6.0?

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

问题描述

我正在Marshmallow 6.0上测试我的应用程序,即使android.permission.READ_EXTERNAL_STORAGE.我在某处读到,如果我在运行时请求权限,则不会强制关闭您的应用程序.我还阅读了此android文档,该文档用于请求运行时权限.

I am testing my app on Marshmallow 6.0 and it's getting force closed for the android.permission.READ_EXTERNAL_STORAGE, even if it is defined in the Manifest already. Somewhere I have read that if I request permission at runtime then it would not force close your application. I have read this android document also, which is for requesting runtime permission.

因此,我知道我们可以请求一个如下所示的权限,该权限在android文档中有所提及.

So, I came to know that we can request a permission like below which is mentioned in the android document.

// Here, thisActivity is the current activity
if (ContextCompat.checkSelfPermission(thisActivity,
                Manifest.permission.READ_CONTACTS)
        != PackageManager.PERMISSION_GRANTED) {

    // Should we show an explanation?
    if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
            Manifest.permission.READ_CONTACTS)) {

        // Show an expanation to the user *asynchronously* -- don't block
        // this thread waiting for the user's response! After the user
        // sees the explanation, try again to request the permission.

    } else {

        // No explanation needed, we can request the permission.

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

        // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
        // app-defined int constant. The callback method gets the
        // result of the request.
    }
}

上面的代码有一个回调方法onRequestPermissionsResult,它获取结果.

The above code has a callback method onRequestPermissionsResult which gets the result.

@Override
public void onRequestPermissionsResult(int requestCode,
        String permissions[], int[] grantResults) {
    switch (requestCode) {

     }
}

我的问题是要向用户确切请求权限?我们应该在应用启动时使用请求权限还是应该在需要权限时使用请求权限?

My question is where to exactly request the permission to user? Should we use the requesting permission at start of the app or should we do it as when the permission is required?

推荐答案

通常,在需要时立即请求所需的权限.通过这种方式,您可以通知用户为什么需要权限,并轻松处理拒绝权限.

In general, request needed permissions it as soon as you need them. This way you can inform the user why you need the permission and handle permission denies much easier.

请考虑以下情况:用户在应用程序运行时撤消了该权限:如果您在启动时请求该权限,而以后再也不进行检查,则可能会导致意外的行为或异常.

Think of scenarios where the user revokes the permission while your app runs: If you request it at startup and never check it later this could lead to unexpected behaviour or exceptions.

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

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