DownloadManager - Rename download if file already exists - android

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.

Related

How to download image from Webview to custom/private folder instead of Download folder in Android

I am trying to download image from webview in custom folder of Android app. As of now i can only download file in Download folder by using below code.
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(imgUrl));
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
DownloadManager downloadManager = (DownloadManager) getActivity().getSystemService(DOWNLOAD_SERVICE);
downloadManager.enqueue(request);
Is there any way to store image in other folder (newly created folder) instead of default Download folder. Actually i want to download image in Android app folder that will be private and not accessible to user via File Manager or other Apps.
I tried to create folder by using following code but folder is creating under /Android/data/com.abc.xyz/ is there any way to create folder directly under internal storage (under root directory) ?
File direct = new File(Environment.getExternalStorageDirectory()+"folder_name");
if(!direct.exists()) {
if(direct.mkdir());
}
try this
mywebView.setDownloadListener(new DownloadListener() {
public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
Request request = new Request(Uri.parse(url));
request.allowScanningByMediaScanner();
request.setNotificationVisibility(
DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
File folder = new File("/storage/emulated/0/Folder_Name");
if (!folder.exists()) {
folder.mkdirs();
System.out.println("Directory created");
} else {
System.out.println("Directory is not created");
}
request.setDestinationInExternalPublicDir("Folder_Name","Wallpaper.jpg");
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
dm.enqueue(request);
}
});

Check If File Exists Before downloading the file

I am using download manager to download the file. The code for downloading the file is as follow.
private String DownloadData(Uri uri, View v, String textview) {
long downloadReference;
// Create request for android download manager
dm = (DownloadManager)getContext().getSystemService(DOWNLOAD_SERVICE);
DownloadManager.Request request = new DownloadManager.Request(uri);
//Setting title of request
request.setTitle(textview);
//Setting description of request
request.setDescription("Android Data download using DownloadManager.");
//Set the local destination for the downloaded file to a path within the application's external files directory
request.setDestinationInExternalFilesDir(getContext(), DIRECTORY_DOWNLOADS, File.separator + "Dr_Israr_Ahmad" + File.separator + textview+".mp3");
//Enqueue download and save into referenceId
downloadReference = dm.enqueue(request);
return null
}
The above code works fine. What i need to do now is if the file is already downloaded than i want my app to play it. The code which is used is
String path = String.valueOf(getContext().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS+ File.separator+"Dr_Israr_Ahmad" + File.separator +filename+".mp3"));
File file = new File(path);
if(file.exists()){
Toast.makeText(getContext(),path+ "/n exists", Toast.LENGTH_SHORT).show();
} else if (!file.exists()) {
Toast.makeText(getContext(), "Downloading", Toast.LENGTH_SHORT).show();
Uri uri = Uri.parse("http://www.digitalsguide.com/mobile-apps/dr-israr-ahmad/audios/"+filename+".mp3");
String filepath = DownloadData(uri,view,filename);
}
but the problem is the condition is true even if the file doesn't exist. Is there a problem in my path ? kindly help me out,
I detected some strange behavior with exists time ago and changed it to isFile:
File file = new File(path);
if (file.isFile()) {
Toast.makeText(getContext(), path + "/n exists", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getContext(), "Downloading", Toast.LENGTH_SHORT).show();
// ...
}
I think the mobile, somehow, created a directory every time new File() was executed.
Check this.
Because getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS) returns /storage/emulated/0/Android/data/<PACKAGE_ID>/files/Download. It's not the folder where DownloadManager downloads files when we set Environment.DIRECTORY_DOWNLOADS.
Try to put your path like the example shown below:
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)+ "/" +filename);
Here filename is example.pdf
you can then check if file exists or not
.getExternalFilesDir(yourFilePath) creates a directory in your code. so use it like this.
String path = String.valueOf(getContext().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)+ File.separator+"Dr_Israr_Ahmad" + File.separator +filename+".mp3");

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

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