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

Download Manager - setting file extension without hardcoding

我想下载一个可以是任何扩展名的文件,使用不包含文件类型的 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