Android M用户权限错误-读取并写入 [英] Android M User Permission Error - READ and WRITE

查看:112
本文介绍了Android M用户权限错误-读取并写入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚开始使用android M,但无法访问外部存储.我收到以下错误

I just started off with android M and I am unable to access the external storage. I get the following error

Caused by: java.lang.SecurityException: Permission Denial: reading 
com.android.providers.media.MediaProvider uri 
content://media/external/images/media from pid=15355, uid=10053 requires 
android.permission.READ_EXTERNAL_STORAGE, or grantUriPermission() 

我正在清单

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

我的构建文件具有以下设置:

and my build file is with following settings :

compileSdkVersion 23
buildToolsVersion "22.0.1"

minSdkVersion 16
targetSdkVersion 23

如何在android M中从外部存储读取和写入?

How to read and write from external storage in android M?

推荐答案

文档中读取>.我必须在运行时请求用户许可.代码示例:

Reading from the documentation. I have to ask user for permission at runtime. Code example :

向android清单添加权限,就像我们以前所做的那样:

Add permission to android manifest like we used to do earlier :

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

检查用户是否已授予权限.如果是,请跳过请求许可并继续您的工作流程,否则请向用户请求许可:

Check if the user has already granted the permission. If yes, skip asking for permission and continue with your work flow else ask user for permission :

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    if (!Settings.System.canWrite(this)) {
        requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE}, 2909);
    } else {
        // continue with your code
    }
} else {
    // continue with your code
}

现在要检查用户是授予许可还是拒绝许可@Override OnRequestPermissionResult以获得回调:

Now to check if the user granted the permission or denied it @Override OnRequestPermissionResult to get a callback :

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    switch (requestCode) {
        case 2909: {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Log.e("Permission", "Granted");
            } else {
                Log.e("Permission", "Denied");
            }
            return;
        }
    }
}

我仅通过询问WRITE就无法读取外部存储 许可,所以我不得不要求 Manifest.permission.READ_EXTERNAL_STORAGE.

I was not able to READ external storage only by asking WRITE permission, so i had to request for Manifest.permission.READ_EXTERNAL_STORAGE as well.


此外,如果您要定位api 23以下的版本,请检查Build 使用IF语句在运行时提供VERSION,仅在以下情况下请求权限 VERSION等于或大于Android M.

Also if you want to target versions below api 23, check the Build VERSION at runtime with IF statement and ask for permissions only if VERSION is equal or above Android M.

这篇关于Android M用户权限错误-读取并写入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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