Android Studio 2.1.2,API 23
Error:
java.lang.SecurityException:无权写入 to / storage / emulated / 0 / Download / aabd.pdf:用户10059也不是 当前进程有android.permission.WRITE_EXTERNAL_STORAGE。
代码:
File file = new File(Environment.getExternalStoragePublicDirectory
(Environment.DIRECTORY_DOWNLOADS), nameOfFile);
request.setDestinationInExternalPublicDir
(Environment.DIRECTORY_DOWNLOADS, nameOfFile);
request.setVisibleInDownloadsUi(true);
myDownloadReference = downloadManager.enqueue(request);
在设备中,它工作正常。
在Manifest中有权限
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.player">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_DOWNLOAD_MANAGER" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
答案 0 :(得分:1)
如果你有targetSdk 23
,你必须检查这样的权限 if (Build.VERSION.SDK_INT == Build.VERSION_CODES.M) {
checkPermission();
}
else {
File file = new File(Environment.getExternalStoragePublicDirectory
(Environment.DIRECTORY_DOWNLOADS), nameOfFile);
request.setDestinationInExternalPublicDir
(Environment.DIRECTORY_DOWNLOADS, nameOfFile);
request.setVisibleInDownloadsUi(true);
myDownloadReference = downloadManager.enqueue(request);
}
private void checkPermission() {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(this,
Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {//Can add more as per requirement
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE},
123);
} else {
}
}
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case 123: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
File file = new File(Environment.getExternalStoragePublicDirectory
(Environment.DIRECTORY_DOWNLOADS), nameOfFile);
request.setDestinationInExternalPublicDir
(Environment.DIRECTORY_DOWNLOADS, nameOfFile);
request.setVisibleInDownloadsUi(true);
myDownloadReference = downloadManager.enqueue(request);
} else {
checkPermission();
}
return;
}
}
}
答案 1 :(得分:0)
是否在模拟器中启用了sd卡仿真?你可能想使用Genymotion模拟器而不是内置的