如何在API 28或Android Pie中使用下载管理器下载文件



正在将异常写入包java.lang.IllegalStateException:不是标准目录之一:/storage/emulated/0/Android/data

DownloadManager dm = (DownloadManager) context.getSystemService(DOWNLOAD_SERVICE);
Uri uri = Uri.parse(s);
DownloadManager.Request req = new DownloadManager.Request(uri);
req.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
String filename = VideoTitle;
filename += ".mp4";
req.setDestinationInExternalPublicDir(context.getResources().getString(R.string.video_dir_path), filename);
req.setDestinationInExternalFilesDir(context,dir_path,filename);
StyleableToast.makeText(context,context.getResources().getString(R.string.download_started), Toast.LENGTH_SHORT, R.style.mytoast).show();
Long ref = dm.enqueue(req);

如何解决此错误

我相信问题出在你提到的那一行。您设置的串联是将文件的目录更改为非标准目录。

例如:

request.setDestinationInExternalPublicDir(getExternalFilesDir(Environment.DIRECTORY_PICTURES) + "/NewFile","abc.jpg")

错误表明了这一点。请查看行告诉您要保存到的目录

像这样的

/storage/emulated/0/Android/data/com.a.b.downloadmanager/files/Pictures/NewFile

所以当你这样做的时候,它会试图保存为

/storage/emulated/0/Android/data/com.a.b.downloadmanager/files/Pictures/NewFile/abc.jpg

解决方法是将文件保存到标准目录中。要做到这一点,您只需要删除连接即可。

例如:

request.setDestinationInExternalPublicDir(getExternalFilesDir(Environment.DIRECTORY_PICTURES),"abc.jpg")

然后它将尝试保存到标准目录

/storage/emulated/0/Android/data/com.a.b.downloadmanager/files/Pictures/abc.jpg

确保你有

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

确保你有

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

manifest.xml

此外,如果您正在使用模拟器,请确保使用SD卡存储创建了模拟器。它不是由默认创建的。