I am trying to download files inside my Webview. I use DownloladListener to handle download request and then I use DownloadManager to download file. Everything works well but I can't get name and extension of file from url's like this one: http://unionpeer.com/dl.php?t=1502119 (This is assassins creed movie .torrent file). How can I get at least file extension? Thanks in advance!
Downloading the file:
String url = (String) objects[0];
String defaultDownloadPath = String.valueOf(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS));
DownloadManager dm = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE)
.setAllowedOverRoaming(true).setTitle(getFileName(url))
.setDescription("Download")
.setDestinationInExternalPublicDir(getPublicExternalPath(defaultDownloadPath),
getFileName(url));
dm.enqueue(request);
getfileName() - works a little better than URLUtils.guessFileNameFromUrl()
String temp = "";
String extension = url.substring(url.lastIndexOf("."));
for (int i = 0; i < extension.length(); i++) {
if (i != 0){
if (!Character.isLetter(extension.charAt(i)) && !Character.isDigit(extension.charAt(i))) {
break;
}
}
temp += extension.charAt(i);
}
return String.valueOf(System.currentTimeMillis() + temp);
Related
I am trying to download Audio files into one of the directories owned by the application using DownloadManager.
Here is my code:
File file = new File(context.getExternalFilesDir(Environment.DIRECTORY_MUSIC),
audioName + ".mp3");
if (file.exists()) {
return;
} else {
DownloadManager mgr = (DownloadManager) context.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).setAllowedOverMetered(true)
.setAllowedOverRoaming(true).setVisibleInDownloadsUi(false)
.setDestinationUri(Uri.fromFile(file));
mgr.enqueue(request);
}
The problem is that downloadManager is duplicating already downloaded audios, for exemple if I have an audio file named "test.mp3" I would find both "test.mp3" and "test1.mp3" in my application directory.
Am I doing something wrong?
Please keep in mind that I want to download files in the app directory and this is why I am using setDestinationUri
I had the same issue. Up to date what I have realized is that the download manager rarely stops downloading and will keep doing so and appending values to the same file name. So I suggest going through your destination directory and deleting duplicate files. You can call this method onCreate.
private void cleanUp()
{
String path = "PATH TO YOUR DOWNLOAD DIRECTORY/FOLDER NAME/";
Log.d("Files", "Path: " + path);
File directory = new File(path);
File[] files = directory.listFiles();
Log.d("Files", "Size: "+ files.length);
for (int i = 0; i < files.length; i++)
{
Log.d("Files", "FileName:" + files[i].getName());
for(int j=1;j<files.length;j++)
{
if(files[i].getName().contains("-"+String.valueOf(j)+".mp3")) // format according to how your download manager has renamed the file e.g "-"+String.valueOf(j)+".mp3" for fileName-1.mp3 or String.valueOf(j)+".mp3" for fileName1.mp3
{
toast(files[i].getName());
files[i].delete();
}
}
}
}
I'm developing an application and using built in Android download manager class. I want to download files into a folder called "myApp" (folder already exists). This is what I tried. I also tried different methods to set download location.But they are not working. Please help to fix this issue.
DownloadManager mgr = (DownloadManager) this.getSystemService(Context.DOWNLOAD_SERVICE);
boolean isDownloading = false;
DownloadManager.Query query = new DownloadManager.Query();
query.setFilterByStatus(
DownloadManager.STATUS_PAUSED|
DownloadManager.STATUS_PENDING|
DownloadManager.STATUS_RUNNING|
DownloadManager.STATUS_SUCCESSFUL
);
Cursor cur = mgr.query(query);
int col = cur.getColumnIndex(
DownloadManager.COLUMN_LOCAL_FILENAME);
for(cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext()) {
isDownloading = isDownloading || ("local file path" == cur.getString(col));
}
cur.close();
if (!isDownloading) {
Uri source = Uri.parse(myWebsites[j]);
Uri dst_uri = Uri.parse("file:///mnt/sdcard/Signagee");
DownloadManager.Request request = new DownloadManager.Request(source);
request.setDestinationUri(dst_uri);
request.setNotificationVisibility(
DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED
);
request.allowScanningByMediaScanner();
long id = mgr.enqueue(request);
}
Use this
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
All the downloads will get downloaded in Downloads folder. You can choose any other destination from the Environment class.
To get the file name check this
String filePath = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME));
filename = filePath.substring( filePath.lastIndexOf('/')+1, filePath.length() );
Use this filename in above line
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);
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;
}
});
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