本文介绍了Marshmallow 中的存储权限错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Lollipop 中,下载功能在我的应用中运行良好,但是当我升级到 Marshmallow 时,当我尝试从互联网下载到 SD 卡时,我的应用崩溃并出现此错误:

In Lollipop, the download functionality works fine in my app, but when I upgraded to Marshmallow, my app crashes and gives this error when I try to download from the internet into the SD card:

Neither user  nor current process has android.permission.WRITE_EXTERNAL_STORAGE

它抱怨这行代码:

DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);

我在应用程序外的清单中拥有权限:

I have the permissions in the manifest outside application:

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

我清理并重建了项目,但它仍然崩溃.

I cleaned and rebuilt the project, but it still crashes.

推荐答案

您应该使用以下方法检查用户是否已授予外部存储权限:

You should be checking if the user has granted permission of external storage by using:

if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
    Log.v(TAG,"Permission is granted");
    //File write logic here
    return true;
}

如果没有,您需要请求用户授予您的应用权限:

If not, you need to ask the user to grant your app a permission:

ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE);

当然,这些仅适用于 marshmallow 设备,因此您需要检查您的应用是否在 Marshmallow 上运行:

Of course these are for marshmallow devices only so you need to check if your app is running on Marshmallow:

 if (Build.VERSION.SDK_INT >= 23) {
      //do your check here
 }

还要确保您的 Activity 实现了 OnRequestPermissionResult

Be also sure that your activity implements OnRequestPermissionResult

整个权限如下所示:

public  boolean isStoragePermissionGranted() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
                == PackageManager.PERMISSION_GRANTED) {
            Log.v(TAG,"Permission is granted");
            return true;
        } else {

            Log.v(TAG,"Permission is revoked");
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
            return false;
        }
    }
    else { //permission is automatically granted on sdk<23 upon installation
        Log.v(TAG,"Permission is granted");
        return true;
    }
}

权限结果回调:

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
        Log.v(TAG,"Permission: "+permissions[0]+ "was "+grantResults[0]);
        //resume tasks needing this permission
    }
}

这篇关于Marshmallow 中的存储权限错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-07 23:12