how to download and save media files in internal storage android java

11.4k Views Asked by At

I want to download some audio files from the internet. I want to use downloadmanager to download this file but I don't know how to save these files to a specific internal storage location in android. InternalStorage/folder/filename.mp3 (so I can access them easily).

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);

It is useful for downloading. But we cannot specify the location for these files.

So how to specify these files to be saved in the internal storage at a specific location. And also, how to access and delete these files.

Please don't devote this question as I got confused while going through many articles.

if any other better alternative or any suggestion comment down

2

There are 2 best solutions below

2
On BEST ANSWER

simply add this line to save file:

request.setDestinationInExternalFilesDir(context,Environment.DIRECTORY_ALARM,mp3name);  

to delete this file

File file = new 
File(context.getExternalFilesDir(Environment.DIRECTORY_ALARMS),"Fav_Ringtone.mp3");

file.delete();

to read this file

File file= newFile(context.getExternalFilesDir(Environment.DIRECTORY_ALARMS),"Fav_Ringtone.mp3");
5
On

Check the request.setDestination functions here To Store file in External App-Specific Directory [example: "external/Android/data/your_app_name/filePath_you_set_in_function”], use like below:

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);

And if you want to download it to another place you need to move it after your download gets finished, by using IO streams. You can use a broadcast receiver to perform this task once the DownloadManager has finished downloading. You can use FileProvider to open the file with another app in Android version 10 or above.