Marshmallow中的存储权限错误在Lollipop中,下载功能在我的应用程序中运行良好,但是当我升级到Marshmallow时,我的应用程序崩溃并在我尝试从互联网下载到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" />我清理并重建了项目,但它仍然崩溃。
4 回答
翻过高山走不出你
TA贡献1875条经验 获得超3个赞
您应该使用以下方法检查用户是否已授予外部存储权限:
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);
当然这些仅适用于棉花糖设备,因此您需要检查您的应用是否在Marshmallow上运行:
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; }}
权限结果回调:
@Overridepublic 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 }}
红颜莎娜
TA贡献1842条经验 获得超12个赞
除非有明确要求在外部存储上写入,否则您始终可以选择将文件保存在app目录中。在我的情况下,我不得不保存文件,浪费了2至3天后,我发现我是否更改了存储路径
Environment.getExternalStorageDirectory()
至
getApplicationContext().getFilesDir().getPath() //which returns the internal app files directory path
它在所有设备上都像魅力一样。这是因为要在外部存储上写入,您需要额外的权限,但在内部应用程序目录中编写很简单。
添加回答
举报
0/150
提交
取消