java - 下载管理器 - 设置文件扩展名而无需硬编码

标签 java android android-download-manager

我想使用不包含文件类型的 URL 下载任何扩展名的文件。对文件类型进行硬编码在这里不起作用。

Uri downloadUrl = Uri.parse(link); 
DownloadManager.Request request = new DownloadManager.Request(downloadUrl);
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
request.setAllowedOverRoaming(true);
request.setTitle(title);
request.setDescription(description); 
request.setVisibleInDownloadsUi(true);
request.setMimeType("application/pdf"); 
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, subDirectory);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
DownloadManager downloadManager = (DownloadManager) context.getSystemService(DOWNLOAD_SERVICE);
if (downloadManager != null) {
    downloadManager.enqueue(request);
}

最佳答案

试试这个:

File file=new File(getExternalFilesDir(null),"Dummy");
/*
Create a DownloadManager.Request with all the information necessary to start the download
*/
DownloadManager.Request request = 
    new DownloadManager.Request(Uri.parse("YOUR URL"))
       .setTitle("Dummy File")// Title of the Download Notification
       .setDescription("Downloading")// Description of the Download Notification
       .setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE)// Visibility of the download Notification
       .setDestinationUri(Uri.fromFile(file))// Uri of the destination file
       .setRequiresCharging(false)// Set if charging is required to begin the download
       .setAllowedOverMetered(true)// Set if download is allowed on Mobile network
       .setAllowedOverRoaming(true);// Set if download is allowed on roaming network

然后:

DownloadManager downloadManager= 
    (DownloadManager) getSystemService(DOWNLOAD_SERVICE);

// enqueue puts the download request in the queue.
downloadID = downloadManager.enqueue(request);

完整示例请参阅link .

关于java - 下载管理器 - 设置文件扩展名而无需硬编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56423406/

相关文章:

java - fragment 无法在旋转时恢复正确的 View

java - 您推荐哪种 Swing 布局?

java - 如何获取ant文件中的属性数量?

java - Android Studio 无法解析符号 "container"和 "PlaceHolderFragment"

android - 下载的文件在 Android 4.4.2 中丢失

android - 我们可以为 android.os.DownloadManager 设置自定义通知吗?

java - 获取标题假装 netflix

Android SQLite 数据库 onCreate 错误

带有 Facebook 登录的 Android WebView

Android Web 查看下载文件 "Can' t 打开文件”消息