问题描述
我想从互联网上下载一些音频文件。我想使用 downloadmanager 下载此文件,但我不知道如何将这些文件保存到 android 中的特定内部存储位置。 InternalStorage/folder/filename.mp3
(以便我可以轻松访问它们)。
manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
Uri uri = Uri.parse("URL");
DownloadManager.Request request = new DownloadManager.Request(uri);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
long reference = manager.enqueue(request);
下载很有用。但我们无法指定这些文件的位置。
那么如何指定这些文件保存在内部存储器的特定位置。还有,如何access
和delete
这些文件。
请不要提出这个问题,因为我在阅读许多文章时感到困惑。
如果有其他更好的选择或任何建议评论
解决方法
检查 request.setDestination 函数 here 要将文件存储在外部应用程序特定目录中 [示例:“external/Android/data/your_app_name/filePath_you_set_in_function”],请使用如下所示:
DownloadManager.Request request = new DownloadManager.Request(uri);
request.setDescription("Selected Video is being downloaded");
request.allowScanningByMediaScanner();
request.setTitle("Downloading Video");
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
//Set the local destination for the downloaded file to a path within the application's external files directory
request.setDestinationInExternalFilesDir(context,Environment.DIRECTORY_DOWNLOADS,fileName); //To Store file in External Public Directory use "setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,fileName)"
DownloadManager manager = (DownloadManager)
mContext.getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);
如果您想将其下载到另一个地方,您需要在下载完成后使用 IO 流将其移动。一旦 DownloadManager 完成下载,您就可以使用广播接收器来执行此任务。您可以使用 FileProvider 在 Android 10 或更高版本中使用其他应用打开文件。
,只需添加这一行即可保存文件:
request.setDestinationInExternalFilesDir(context,Environment.DIRECTORY_ALARM,mp3name);
删除这个文件
File file = new
File(context.getExternalFilesDir(Environment.DIRECTORY_ALARMS),"Fav_Ringtone.mp3");
file.delete();
读取这个文件
File file= newFile(context.getExternalFilesDir(Environment.DIRECTORY_ALARMS),"Fav_Ringtone.mp3");