gpt4 book ai didi

Android M 用户权限错误 - 读写

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:33:24 25 4
gpt4 key购买 nike

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

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

我在 list 中添加用户权限,如

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

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

compileSdkVersion 23
buildToolsVersion "22.0.1"

minSdkVersion 16
targetSdkVersion 23

如何在android M 中读写外部存储?

最佳答案

documentation 读取.我必须在运行时请求用户许可。代码示例:

像我们之前做的那样向 android manifest 添加权限:

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

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

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 以获得回调:

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

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.


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 用户权限错误 - 读写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32175770/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com