问题描述
下载管理器在 Android 10 设备上收到以下错误。目标版本为 29。
我在 Manifest 中添加了 android:requestLegacyExternalStorage="true"
标签,但它不起作用。
java.lang.SecurityException: 不支持的路径 /storage/emulated/0/Contents/Awesome App.apk
这是代码
public static void startDownload(Context context,String url,String token,String subPath) {
DownloadManager.Request request;
DownloadManager manager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
Uri uri = Uri.parse(url); // A url to download a file
try {
request = new DownloadManager.Request(uri);
request.addRequestHeader("X-Auth-Token",token);
} catch (IllegalArgumentException e) {
e.printstacktrace();
return;
}
request.setVisibleInDownloadsUi(true);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
try {
File downloadFileDir = new File(Environment
.getExternalStorageDirectory().getAbsolutePath() + "/Contents");
if (downloadFileDir != null) {
if (!downloadFileDir.exists()) {
downloadFileDir.mkdirs();
}
File file = new File(downloadFileDir.getAbsolutePath() + File.separator + subPath);
// subPath is name of the file to download. e.g. Awesome App.apk
if (file.exists()) {
file.delete();
}
Uri localUri = Uri.fromFile(file);
request.setDestinationUri(localUri);
if (localUri != null) {
request.setMimeType(MimeTypeMap.getSingleton().getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(localUri.toString())));
}
}
} catch (SecurityException e) {
e.printstacktrace();
}
request.setTitle(subPath);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
try {
manager.enqueue(request);
} catch (SecurityException e) {
e.printstacktrace();
//Got exception here
}
}
解决方法
/storage/emulated/0/Contents/Awesome App.apk
在 Android 10 设备中,DownloadManager 不会下载到您自己的外部存储目录中。
您需要使用已经可用的公共目录之一,例如 Document、Download、DCIM、Music 等。
所以你可以让下载到
/storage/emulated/0/Music/Contents/Awesome App.apk
无需自己创建子目录,因为下载管理器会这样做。
您的应用无需任何权限即可让下载管理器执行其任务。