How to replace files in same location using Download manager in Android? - android

In my app I need to download some files(images,Pdf&txt). I am successful to save files through download manager in Downloads folder, But I want if file already exist in downloads folder and user again click on same file then it delete older one in download folder and replace with new file. Please let me know how it is possible?
My code:
database = new DMS_Database(Files_Folders_Activity.this);
if(!database.dididExist((doc_Id))) // if file does not exist then it will save file in the database and in downloads folder.
{
database.Save_Doc(doc_Id, name, url); //Database method
System.out.println("you are here: Save Files");
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setTitle(name);
// in order for this if to run, you must use the android 3.2 to compile your app
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
{
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
}
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS + "/Downloads", name);
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);
}
else
{
database.update_Doc(Doc_Id,name,url);
//But if file already exist then How to delete file and again save on same location. I don't want duplicate file. Right now it is creating two websites also not updating database.
System.out.println("you are here: update files");
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setTitle(name);
// in order for this if to run, you must use the android 3.2 to compile your app
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
{
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
}
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS + "/Downloads", name);
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);
}
database.close();
Please let mek now ow it is possible, thanks.

Related

How I can download video in my application like we download or install apk file on google play?

I want to download video from URL in background like we install apk file in background from Google play. I want to show downloading indicator on notification bar same like it showing while we download or install apk file. if any suggestion or idea then suggest me how I can achieve this task in my project.
You can prefer android DownLoadManager. somehow want to do like this in your activity
String mUrl="your video url";
DownloadManager manager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
Request request = new Request(Uri.parse(mUrl));
request.setDestinationInExternalFilesDir(getApplicationContext(), Environment.DIRECTORY_DOWNLOADS, your_fileName);
request.setNotificationVisibility(Request.VISIBILITY_VISIBLE);
request.setAllowedOverRoaming(false);
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
manager.enqueue(request);
setNotificationVisibility() -> show download notification in notification bar(window) with download progress also.
below are three methods where you can choose destination for your downloaded file path.
1. setDestinationInExternalFilesDir(Context context, String dirType, String subPath)
Set the local destination for the downloaded file to a path within the application's external files directory (as returned by getExternalFilesDir(String).
2. setDestinationInExternalPublicDir(String dirType, String subPath)
Set the local destination for the downloaded file to a path within the public external storage directory (as returned by getExternalStoragePublicDirectory(String)).
3. setDestinationUri(Uri uri)
Set the local destination for the downloaded file.
Use Download Manager,
private void for_call_download() {
File folder = Environment.getExternalStoragePublicDirectory(DOWNLOAD_FOLDER_NAME);
if (!folder.exists() || !folder.isDirectory()) {
folder.mkdirs();
}
try {
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(APK_URL));
request.setDestinationInExternalPublicDir(DOWNLOAD_FOLDER_NAME, DOWNLOAD_FILE_NAME);
request.setTitle(SessionName);
request.setDescription("" + SessionDesc);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setVisibleInDownloadsUi(false);
request.setMimeType("application/cn.trinea.download.file");
downloadId = downloadManager.enqueue(request);
} catch (IllegalStateException i) {
showAlert(context, "Sorry Some Problem");
i.printStackTrace();
}
updateView();
status_download = true;
}

im not getting default file name when i download

i have created a webview app i added downloader inside which download the file end with m4a..the app downloads the file but file name changes...how can get title from the file...
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// handle different requests for different type of files
// this example handles downloads requests for .m4a and .mp3 files
// everything else the webview can handle normally
if (url.endsWith(".m4a")) {
Uri source = Uri.parse(url);
// Make a new request pointing to the .apk url
DownloadManager.Request request = new DownloadManager.Request(source);
// appears the same in Notification bar while downloading
request.setDescription("Description for the DownloadManager Bar");
request.setTitle(getTitle());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
}
// save the file in the "Downloads" folder of SDCARD
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "filename");
// get download service and enqueue file
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);
}
else if(url.endsWith(".mp3")) {
// if the link points to an .mp3 resource do something else
}
// if there is a link to anything else than .m4a or .mp3 load the URL in the webview
else view.loadUrl(url);
return true;
}
});
This will give you your file name
final String[] separated = url.split("/");
final String myFile = separated[separated.length - 1];
It will split the url using the / character and you take the last element in the returned array.
Arrays are 0 based, so the last element is the one located at the vector's length - 1.
Put the above code just before this line: if (url.endsWith(".m4a")) {, where you want to get your file name.
Then, use it so:
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, myFile);
Full code for downloading file inside webview without calling web-browser
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// handle different requests for different type of files
// this example handles downloads requests for .m4a and .mp3 files
// everything else the webview can handle normally
if (url.endsWith(".m4a"))
{
Uri source = Uri.parse(url);
final String[] separated = url.split("/");
final String myFile = separated[separated.length - 1];
// Make a new request pointing to the .apk url
DownloadManager.Request request = new DownloadManager.Request(source);
// appears the same in Notification bar while downloading
request.setDescription("Description for the DownloadManager Bar");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
}
// save the file in the "Downloads" folder of SDCARD
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_MUSIC, myFile);
// get download service and enqueue file
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);
}
else if (url.endsWith(".pdf"))
{
Uri source = Uri.parse(url);
final String[] separated = url.split("/");
final String myFile = separated[separated.length - 1];
// Make a new request pointing to the .apk url
DownloadManager.Request request = new DownloadManager.Request(source);
// appears the same in Notification bar while downloading
request.setDescription("Description for the DownloadManager Bar");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
}
// save the file in the "Downloads" folder of SDCARD
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_MUSIC, myFile);
// get download service and enqueue file
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);
}
// if there is a link to anything else than .m4a or .mp3 load the URL in the webview
else view.loadUrl(url);
return true;
}
});

how to check if file is available in internal storage

I am trying to download a file from the internet and it succeeded but now
I want to check if the file exists in the internal storage.
else if (arg0.getId() == R.id.btn_download)
{
Toast.makeText(this, "download button clicked", Toast.LENGTH_SHORT).show();
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(names[b]));
request.setDescription("Downloading..");
request.setTitle("Futsing Magazine Issue " + (this.mPictureManager.getCurrentIndex() +1) );
// in order for this if to run, you must use the android 3.2 to compile your app
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
}
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "Futsing Magazine Issue " + (this.mPictureManager.getCurrentIndex()
+1) +".pdf");
// get download service and enqueue file
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);
The items retrieved are downloaded to /mnt/sdcard/Download.
How do I check if the file exists or not using code?
Let's say following is your file's path
String path=context.getFilesDir().getAbsolutePath()+"/filename";
File file = new File ( path );
if ( file.exists() )
{
// Toast File is exists
}
else
{
// Toast File is not exists
}
File applictionFile = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS)+ "/"+<file-name>);
if(applictionFile != null && applictionFile.exists()){
}
if file is getting downloads in to default donwload directory

How to save downloaded file on sd card from download manager programmatically on android

In my application i have download(Image) feature which is used to download file from urls. The download happen should be shown in notification bar so that i used Download Manager class to download file. This is working fine but the downloaded image does not stored no where in the sdcard.
i have referred the url for the download manager.
my requirement is i need to save the download image to sdcard with notification bar indication. What to modify on the code to get save image on sdcard on the above link
i have some doubts regards the code in the above link is Can i use the same code to download audio or video file?
please help me.
Edited question:
I have tried
filepath = Environment.getExternalStorageDirectory().getPath()+"/download/cm.png";
Uri destinationUri = Uri.parse(filepath);
request.setDestinationUri(destinationUri);
before the preference manger on the button click. but i could not get the file on sdcard.
This is what i used.
Uri downloadUri = Uri.parse(DOWNLOAD_FILE);
DownloadManager.Request request = new DownloadManager.Request(downloadUri);
request.setDescription("Downloading a file");
long id = downloadManager.enqueue(request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI |DownloadManager.Request.NETWORK_MOBILE)
.setAllowedOverRoaming(false)
.setTitle("File Downloading...")
.setDescription("Image File Download")
.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "cm.png"));
In the code you refer to, the file is opened at the end. At this point, you can consider copying it to the SDCard.
Otherwise (better) use http://developer.android.com/reference/android/app/DownloadManager.Request.html setDestinationUri(android.net.Uri) to specify where you want to download the file.
downloadmanager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
Toast.makeText(context, "Downloading...", Toast.LENGTH_LONG).show();
Uri uri = Uri.parse("---- url here ------");
request = new DownloadManager.Request(uri);
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
request.setAllowedOverRoaming(false);
request.setTitle("---- title here ------");
String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl("---- url here ------");
request.setMimeType(mimeType);
request.setDescription("---- descripation here ------");
if("---- titlehere ------" != null){
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "---- title here ------");
}
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
Long reference = downloadmanager.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