小编典典

Marshmallow 中的存储权限错误

all

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

Neither user  nor current process has android.permission.WRITE_EXTERNAL_STORAGE

它抱怨这行代码:

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

我在应用程序外部清单中具有权限:

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

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


阅读 55

收藏
2022-07-30

共1个答案

小编典典

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

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

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

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

当然,这些仅适用于棉花糖设备,因此您需要检查您的应用程序是否在棉花糖上运行:

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

还要确保您的活动实施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
    }
}
2022-07-30