用于访问图库的Android 6运行时权限

时间:2015-11-13 20:31:01

标签: android-gallery android-6.0-marshmallow android-external-storage runtime-permissions

我对Android 6(Marshmallow)运行时权限有疑问。如果用户想要从图库中选择照片,我们是否应该要求READ_EXTERNAL_STORAGE权限?

即使我关闭了存储权限,我似乎也可以访问该库。

2 个答案:

答案 0 :(得分:4)

您需要提出READ_EXTERNAL_STORAGE。您可以在没有它的情况下访问图库,但如果您想对从图库中获得的媒体做任何事情,则需要READ权限。

快速测试从图库中挑选图像后onActivityResult中发生的事情:

  

权限拒绝:阅读com.android.providers.media.MediaProvider   uri content://来自pid的媒体/外部/图像/媒体= 8405,uid = 10177   需要android.permission.READ_EXTERNAL_STORAGE,或   grantUriPermission()

答案 1 :(得分:0)

对于自定义权限,如果您使用的是Android 6.0或更高版本,则可以使用运行时权限。此代码可能会对您有所帮助。

  

如果您的应用尚未获得所需的权限,则该应用必须   调用requestPermissions()方法之一来请求   适当的权限。您的应用程序会传递它想要的权限,并且   还指定了一个整数请求代码来标识它   许可请求。此方法异步运行:它返回   立即,并在用户响应对话框后,系统   使用结果调用应用程序的回调方法,并传递相同的结果   请求代码,应用程序传递给requestPermissions()。

// 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 explanation 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.
    }
}    
  

To Know more about runtime permission

https://developer.android.com/training/permissions/requesting.html