i'm using the Download Manager class to download Mp3 files .
DownloadManager downloadManager = (DownloadManager)getSystemService(Context.DOWNLOAD_SERVICE);
//dls is an arraylist that holds the download links
Uri uri=Uri.parse(dls.get(0));
DownloadManager.Request request= new DownloadManager.Request(uri);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,"file.mp3");
downloadManager.enqueue(request);
the setDestinationInExternalPublicDir
method requires a second parameter that will change the name of the downloaded file .
I want the file to have its default name . If i dont use the method the file will have its default name but it wont be located in the Download directory .
How can i achieve both , locate the file in the Download directory and leave the name of the file as it is ?
thanks for help.
Can you try this:
public static String getFileNameFromURL(String url) {
if (url == null) {
return "";
}
try {
URL resource = new URL(url);
String host = resource.getHost();
if (host.length() > 0 && url.endsWith(host)) {
// handle ...example.com
return "";
}
}
catch(MalformedURLException e) {
return "";
}
int startIndex = url.lastIndexOf('/') + 1;
int length = url.length();
// find end index for ?
int lastQMPos = url.lastIndexOf('?');
if (lastQMPos == -1) {
lastQMPos = length;
}
// find end index for #
int lastHashPos = url.lastIndexOf('#');
if (lastHashPos == -1) {
lastHashPos = length;
}
// calculate the end index
int endIndex = Math.min(lastQMPos, lastHashPos);
return url.substring(startIndex, endIndex);
}
This method can handle these type of input:
Input: "null" Output: ""
Input: "" Output: ""
Input: "file:///home/user/test.html" Output: "test.html"
Input: "file:///home/user/test.html?id=902" Output: "test.html"
Input: "file:///home/user/test.html#footer" Output: "test.html"
Input: "http://example.com" Output: ""
Input: "http://www.example.com" Output: ""
Input: "http://www.example.txt" Output: ""
Input: "http://example.com/" Output: ""
Input: "http://example.com/a/b/c/test.html" Output: "test.html"
Input: "http://example.com/a/b/c/test.html?param=value" Output: "test.html"
Input: "http://example.com/a/b/c/test.html#anchor" Output: "test.html"
Input: "http://example.com/a/b/c/test.html#anchor?param=value" Output: "test.html"
You can find the whole source code here: https://ideone.com/uFWxTL