Store media in internal storage using download manager - android

Want to store music file inside getFilesDir() using Uri. I had tried to store by this way
Uri Download_Uri = Uri.parse(songBean.vSongsFileName);
DownloadManager.Request request = new DownloadManager.Request(Download_Uri);
mDownloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
request.setAllowedOverRoaming(false);
request.setTitle(songBean.vTitle);
request.setDescription("Downloading File");
try {
request.setDestinationUri(Uri.parse(createDirectory("tmp.mp3").getPath()));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
downloadReference = mDownloadManager.enqueue(request);
registerReceiver(new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
}
}, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
Method for the create directory inside internal storage
public File createDirectory(String filename) throws FileNotFoundException {
File file = new File(context.getFilesDir(), filename);
Log.i("Tag", "createDirectory: " + file.getAbsolutePath());
return file;
}
Not able to store the file in internal storage.request.setDestinationUri(Uri.parse(createDirectory("tmp.mp3").getPath())); throwing not a file uri error.Please help me out for this

The getFilesDir() is private internal storage for your app only. You cannot ask another app to put files there as it has no access.
For DownloadManager use external storage.

Related

DownloadManager throws SecurityException on Android Q

Download Manager gets the error below on Android 10 devices. The target version is 29.
I added android:requestLegacyExternalStorage="true" tag to the Manifest, but it didn't work.
java.lang.SecurityException: Unsupported path /storage/emulated/0/Contents/Awesome App.apk
Here is the code
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
In an Android 10 device the DownloadManager will not download to your own directories on external storage.
You need to use one of the already available public directories like Document, Download, DCIM, Music and so on.
So you can let download to
/storage/emulated/0/Music/Contents/Awesome App.apk
No need to create your subdirectory yourself as the download manager will do it.
You app does not need any permission to let the download manager execute its task.

How to make downloaded file visible in Gallery in Android Q?

I am using download manager to download file like so:
DownloadManager.Request request = new DownloadManager.Request(uri);
request.setTitle(createTitle());
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalFilesDir(activity, Environment.DIRECTORY_DOWNLOADS, subFolders + createFileName());
request.allowScanningByMediaScanner();
After it is downloaded, I am adding it to the media store like so:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
ContentValues contentValues = new ContentValues();
ContentResolver database = activity.getContentResolver();
contentValues.put(MediaStore.Downloads.DISPLAY_NAME, displayName);
contentValues.put(MediaStore.Downloads.MIME_TYPE, mimeType);
contentValues.put(MediaStore.Downloads.RELATIVE_PATH, Environment.DIRECTORY_DOWNLOADS + "/subfolder");
database.insert(MediaStore.Downloads.EXTERNAL_CONTENT_URI, contentValues);
}
I will see the folder created in the gallery but the file always shows up as corrupted.
Can anyone help ?
To be able to load or view your downloaded image in gallery you need to scan the saved file using MediaScannerConnection:
private void scanFile(String path) {
MediaScannerConnection.scanFile(context,
new String[] { path }, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.d("Tag", "Scan finished. You can view the image in the gallery now.");
}
});
}
Call this after you create your file path or in your checking if the file does exist:
scanFile(filePath);
Hope it will work :)

Can't play mp3 file from internal storage into media player

I am downloading mp3 file from this url using DownloadManager. Here is my code.
// Downloading file from internet and save to internal storage.
private void downloadFromOnline() {
downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
DownloadManager.Request request = null;
request = new DownloadManager.Request(Uri.parse("https://alquran.technobdapis.com/quranallaudio/arabic_with_bangla/arbn_001.mp3"));
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
request.setAllowedOverRoaming(false);
request.setTitle("Downloading...");
request.setDescription("Downloading...arbn_001.mp3");
request.setVisibleInDownloadsUi(true);
File SDCardpath = getFilesDir();
File myDataPath = new File(SDCardpath.getAbsolutePath());
// Internal storage file path to save the downloaded file
// /data/data/com.technobd.internalstoragetest/files/arabic_with_bangla/arbn_001.mp3
if (!myDataPath.exists())
myDataPath.mkdir();
request.setDestinationInExternalFilesDir(getApplicationContext(), myDataPath.getPath() + "/arabic_with_bangla", "arbn_001.mp3");
long refid = downloadManager.enqueue(request);
id = refid;
}
I have tried to play the downloaded file in media player using this code. But unfortunately targetFile.exists() returns false although file exists in that path. Here is the code -
public BroadcastReceiver onComplete = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
File SDCardpath = getFilesDir();
File myDataPath = new File(SDCardpath.getAbsolutePath());
File targetFile = new File(myDataPath.getPath() + "/arabic_with_bangla/" +"arbn_001.mp3");
Log.d("FileExists", targetFile.exists() + " ");
// Downloaded file path
// /data/data/com.technobd.internalstoragetest/files/arabic_with_bangla/arbn_001.mp3
// Although target file exists in device It's targetFile.exists() returning false
// TODO: This is the main problem.
if(targetFile.exists()){
MediaPlayer mp = new MediaPlayer();
try {
mp.setDataSource(MainActivity.this, Uri.parse(targetFile.getParent()));
mp.prepare();
mp.start();
} catch (Exception e) {
e.printStackTrace();
}
}else{
// File Not Exists
Log.d("FileExists", targetFile.exists() + " ");
}
}
};
File exists in my device.

How to save files with DownloadManager in private path?

I have downloaded some files with DownloadManager, I want to save them where that no one can access them, I mean they are private, just my application can access them and I want after uninstall my app they get deleted. but according to my search DownloadManager can save files just in SDCard that everyone can see my files.
can anyone tell me what to do?
You should probably use:
request.setDestinationInExternalFilesDir(context, DIRECTORY_DOWNLOADS, File.separator + folderName + File.separator + fileName);
Where request is your DownloadManager.Request
This folder (sdcard/Android/data/your.app.package) is accessible to the user, but not visible in galleries (not scanned by media scanner), it's only accessible using file manager. Also, this folder will be deleted when your app gets deleted.
You can use internal storage path to save data internally and it will get deleted when your app will get uninstalled
String dir = getFilesDir().getAbsolutePath();
For Set Your Path For Download File Use: Work For me (Android 11).
File file = new File(Environment.getExternalStorageDirectory().getPath() + "/YOUR FOLDER/", "YOUR FILE.(mp3|mp4|pdf|...)");
request.setDestinationUri(Uri.fromFile(file));
Complete Code:
First Check Directory
private boolean CreateDirectory() {
boolean ret = false;
File filepath = Environment.getExternalStorageDirectory();
File dir = new File(filepath.getPath() + "/YOUR FOLDER/");
if (!dir.exists()) {
try {
dir.mkdirs();
ret = true;
} catch (Exception e) {
ret = false;
e.printStackTrace();
}
}
return ret;
}
Then:
String URL = " YOUR URL ";
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(URL));
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
request.setTitle("YOUR TITLE");
request.setDescription("YOUR DESCRIPTION");
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
File file = new File(Environment.getExternalStorageDirectory().getPath() + "/YOUR FOLDER/", "YOUR FILE.(mp3|mp4|pdf|...)");
request.setDestinationUri(Uri.fromFile(file));
DownloadManager manager=(DownloadManager)getSystemService(Context.DOWNLOAD_SERVICE);
Long downloadId= manager.enqueue(request);
ok,Finish

Set custom folder Android Download Manager

I've a question about Download Manager.
I'm going to download a file from a site. When I set the default directory for download (Environment.DIRECTORY_DOWNLOAD) all works fine and my download is started. But if I try to change the directory, my app doesn't download the file. In particular, I want my file to go into a folder inside a Download, for example /storage/sdcard/Download/myFolder. How can I fix that?
File mydownload = new File (Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)+ "/myFolder");
if (!mydownload.exists()){
mydownload.mkdir();
}
String url = sUrl[0];
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
}
request.setDestinationInExternalPublicDir(mydownload.getAbsolutePath(),"Myfile.extension");
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);
check below code: its save file in "sdcard/dhaval_files/". just replace your folder name and give permission write_external_storage in android manifest file.
public void file_download(String uRl) {
File direct = new File(Environment.getExternalStorageDirectory()
+ "/dhaval_files");
if (!direct.exists()) {
direct.mkdirs();
}
DownloadManager mgr = (DownloadManager) this.getSystemService(Context.DOWNLOAD_SERVICE);
Uri downloadUri = Uri.parse(uRl);
DownloadManager.Request request = new DownloadManager.Request(
downloadUri);
request.setAllowedNetworkTypes(
DownloadManager.Request.NETWORK_WIFI
| DownloadManager.Request.NETWORK_MOBILE)
.setAllowedOverRoaming(false).setTitle("Demo")
.setDescription("Something useful. No, really.")
.setDestinationInExternalPublicDir("/dhaval_files", "test.jpg");
mgr.enqueue(request);
}
There are two options available for you to use.
1) first setDestinationInExternalPublicDir this will let you download in any of the androids standard download folder based on media type eg DIRECTORY_DOWNLOADS, DIRECTORY_MUSIC. these files will remain after uninstall.
request.setDestinationInExternalPublicDir(DIRECTORY_DOWNLOADS,
File.separator + folderName + File.separator + fileName);
The first argument should be a standard downloads directory for this to work properly and cannot be anything else.
2) second is setDestinationInExternalFilesDir this is same as the previous method with the difference that these files will be deleted after app uninstall.
request.setDestinationInExternalFilesDir(context, DIRECTORY_DOWNLOADS,
File.separator + folderName + File.separator + fileName);
here the second argument can be null or any of the android download directories.
Try Below Code:.
String storagePath = Environment.getExternalStorageDirectory()
.getPath()
+ "/Directory_name/";
//Log.d("Strorgae in view",""+storagePath);
File f = new File(storagePath);
if (!f.exists()) {
f.mkdirs();
}
//storagePath.mkdirs();
String pathname = f.toString();
if (!f.exists()) {
f.mkdirs();
}
// Log.d("Storage ",""+pathname);
dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
Uri uri = Uri.parse(image);
checkImage(uri.getLastPathSegment());
if (!downloaded) {
DownloadManager.Request request = new DownloadManager.Request(uri);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir("/Directory_name", uri.getLastPathSegment());
Long referese = dm.enqueue(request);
Toast.makeText(getApplicationContext(), "Downloading...", Toast.LENGTH_SHORT).show();
}
For Set Your Path For Download File Use: Work For me (Android 11).
File file = new File(Environment.getExternalStorageDirectory().getPath() + "/YOUR FOLDER/", "YOUR FILE.(mp3|mp4|pdf|...)");
request.setDestinationUri(Uri.fromFile(file));
Complete Code:
First Check Directory
private boolean CreateDirectory() {
boolean ret = false;
File filepath = Environment.getExternalStorageDirectory();
File dir = new File(filepath.getPath() + "/YOUR FOLDER/");
if (!dir.exists()) {
try {
dir.mkdirs();
ret = true;
} catch (Exception e) {
ret = false;
e.printStackTrace();
}
}
return ret;
}
Then:
String URL = " YOUR URL ";
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(URL));
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
request.setTitle("YOUR TITLE");
request.setDescription("YOUR DESCRIPTION");
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
File file = new File(Environment.getExternalStorageDirectory().getPath() + "/YOUR FOLDER/", "YOUR FILE.(mp3|mp4|pdf|...)");
request.setDestinationUri(Uri.fromFile(file));
DownloadManager manager= (DownloadManager)
getSystemService(Context.DOWNLOAD_SERVICE);
Long downloadId= manager.enqueue(request);
ok,Finish

Categories

Resources