Set custom folder Android Download Manager - android

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

Related

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

how to store downloaded image in internal storage using Download Manager in android

how to save image or mp3 file in internal storage using Download manager
Code:
public void StartDownload(String path)
{
ContextWrapper cw = new ContextWrapper(context);
File directory = cw.getDir("channel" + cId, Context.MODE_PRIVATE);
if (!directory.exists()) {
directory.mkdir();
}
DownloadManager mgr = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
Uri downloadUri = Uri.parse(path);
DownloadManager.Request request = new DownloadManager.Request(
downloadUri);
String imgnm = path.substring(path.lastIndexOf("/") + 1);
startdownloadurl = directory.getAbsolutePath()+"/";
System.out.println(" directory " + startdownloadurl);
request.setAllowedNetworkTypes(
DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE)
.setAllowedOverRoaming(false).setTitle(imgnm)
.setDescription("Downloading...")
.setVisibleInDownloadsUi(true)
.setDestinationInExternalPublicDir(startdownloadurl, imgnm);
mgr.enqueue(request);
}
i m trying to store downloaded image or mp3 file in my internal storage
but it not work well
required path is "data/data/packagename/app_channel1/image1.jpg"

Download Image and store it in Gallery app in android

I want to save Image file in Gallery so that Image can be viewed from the Gallery application.
But what I want is to create a separate dir, as like we have for whatsapp Images etc apps in our gallery application.
So far I have written this code to download an image
public void createDir(){
File dir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), DIR_NAME);
Log.d(LOG_TAG, "dir pictr :" + dir.toString());
if (!dir.exists()) {
dir.mkdir();
Log.d(LOG_TAG, "dir not exists and created first time");
} else {
Log.d(LOG_TAG, "dir exists");
}
}
Above code created directory inside gallery dir
Uri imageLink = Uri.parse(downloadUrlOfImage); // this is download link like www.com/abc.jpg
CreateDir();
DownloadManager.Request request = new DownloadManager.Request(imageLink);
File dir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), DIR_NAME);
String absPath = dir.getAbsoultePath();
request.setDestinationUri(Uri.parse(absPath + "image.jpg"));
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
DownloadManager dm = (DownloadManager) getContext().getSystemService(Context.DOWNLOAD_SERVICE);
dm.enqueue(request);
But this gives me error as java.lang.IllegalArgumentException: Not a file URI: /storage/sdcard0/Pictures/FreeWee/1458148582.jpg
Basically what I want is to save Image and that image must be shown in Gallery Application under Some directory I named.
If not understood please ask, so that I can improve my question.
How do I proceed further ?
As #RoyFalk pointed out you got 2 issues in your code.
So you can go with this code snippet
String filename = "filename.jpg";
String downloadUrlOfImage = "YOUR_LINK_THAT_POINTS_IMG_ON_WEBSITE";
File direct =
new File(Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
.getAbsolutePath() + "/" + DIR_NAME + "/");
if (!direct.exists()) {
direct.mkdir();
Log.d(LOG_TAG, "dir created for first time");
}
DownloadManager dm = (DownloadManager) getContext().getSystemService(Context.DOWNLOAD_SERVICE);
Uri downloadUri = Uri.parse(downloadUrlOfImage);
DownloadManager.Request request = new DownloadManager.Request(downloadUri);
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE)
.setAllowedOverRoaming(false)
.setTitle(filename)
.setMimeType("image/jpeg")
.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
.setDestinationInExternalPublicDir(Environment.DIRECTORY_PICTURES,
File.separator + DIR_NAME + File.separator + filename);
dm.enqueue(request);
And you will see Image inside the gallery application under your DIR_NAME.
Hope this will help you.

How to detect the extension of file to download using DownloadManager in Android?

I start developing my very first Android project. In my project, I need to download media files, especially mp3 or mp4. I am downloading file using DownloadManager.
Here is my download code for mp3
private void downloadPodcast(int id)
{
String url = context.getResources().getString(R.string.api_endpoint)+"podcast/download?id="+String.valueOf(id);
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setDescription("Downloading...");
request.setTitle("Podcast");
request.setMimeType("audio/MP3");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
}
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "audio.mp3");
DownloadManager manager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);
}
As you can see in my code, I am downloading only mp3 and setting the MIME type is constant. The file name and its extension is constant as well. What I want to do is to detect the file extension I will download. So can I set the MIME type programmatically and set the extension of file name. How can I achieve it in DownloadManager?
Though its quite late, however here is the answer:
You can get the extension of the file to download using the code below and add the extension to your file name.
String fileUrl = "http://someurl";
String fileName = "foobar";
String fileExtension = MimeTypeMap.getFileExtensionFromUrl(fileUrl);
// concatinate above fileExtension to fileName
fileName += "." + fileExtension;
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(fileUrl))
.setTitle(context.getString(R.string.app_name))
.setDescription("Downloading " + fileName)
.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE | DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE)
.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
DownloadManager dm = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
dm.enqueue(request);

DownloadManager - Rename download if file already exists

public void onClick(DialogInterface dialog, int id) {
Uri u = Uri.parse(url);
File f = new File("" + u);
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setTitle("");
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, f.getName());
// just my bullshit here please correct here
if (f.exists()) {
File sdcard = Environment.getExternalStorageDirectory();
File from = new File(sdcard,f.getName());
File to = new File(sdcard,"*"+f.getName());
from.renameTo(to);
}
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);
}
I have this little code then when clicked it download file from a url but when the file is already downloaded and have the same name it just show fail, how can I check if file already exist and let the DownloadManager download that file with different name?
The DownloadManager renames files by default when they exist. It will append a -[NUMBER] at the end of the filename.
So hello.jpg is turned to hello-1.jpg.
Maybe have a look at this example. I used it and it works.

Categories

Resources