Android Marshmallow 6.0在运行时请求权限 [英] Request Permission at Runtime for Android Marshmallow 6.0

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

问题描述

我正在 Marshmallow 6.0 上测试我的应用程序,并且它已经关闭 android.permission.READ_EXTERNAL_STORAGE ,即使已经在Manifest中定义了它。在某处我读过,如果我在运行时请求权限,那么它不会强制关闭你的应用程序。我也阅读了这个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天全站免登陆