How to avoid API level warning? - android

I'm trying to make a method to download a file, but inside the method in the request, it has a call to a function that show a notification of the download. The problem is that the minimum api required for my app is API 9, and the IDE shows me an error because setNotificationVisibility is for API 11 and above.
This is my source code:
public void init_download(String title, String filename, String url) {
File path = new File(Environment.DIRECTORY_DOWNLOADS);
if (!path.exists()) {
path.mkdirs();
}
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(title)
.setDescription(getResources().getString(R.string.downloading))
.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, filename);
.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
long id = downloadManager.enqueue(request);
//Save the request id
SharedPreferences.Editor PrefEdit = shared_pref.edit();
PrefEdit.putLong("DOWNLOAD_ID", id);
PrefEdit.commit();
}
How can I solve this to run notifications in both versions?
Thank you.

Add #SuppressLint("NewApi") to the declaration of your functioin, this is:
#SuppressLint("NewApi")
public void init_download(String title, String filename, String url) {
}

You can solve the warning with #SuppressLint("NewApi")but in lower API's your setNotificationVisibility will not work as there is no DownloadManager in support packages.

I've solved the last problem by changing the VISIBILITY of the notification:
public void init_download(String title, String filename, String url) {
File path = new File(Environment.DIRECTORY_DOWNLOADS);
if (!path.exists()) {
path.mkdirs();
}
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(title)
.setDescription(getResources().getString(R.string.downloading))
.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, filename);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
}
else {
request.setShowRunningNotification(true);
}
long id = downloadManager.enqueue(request);
//Save the request id
SharedPreferences.Editor PrefEdit = shared_pref.edit();
PrefEdit.putLong("DOWNLOAD_ID", id);
PrefEdit.commit();
}
This is to download a file to the Downloads directory of your android device.

You should add #SuppressLint("NewApi") before your method. But it will be better to up min sdk version or don't use this method. If you add #SuppressLint("NewApi") don't forget about users that can run you app on device with 9 api.

Related

Download Unsuccessful when using DownloadManager.Request to download the file from url

I'm trying to download the file from the server using DownloadManager but It fail's to download and say's Download unsuccessful, I have read that there is a issue with Download Manager in the below link
android-chrome-browser-unnecessarily-renames-names-types-of-downloaded-files so I tried to download the file by adding the RequestHeader to the DownloadManagerRequest using below method but nothing happened. please find the below code part of my Downloader class anyone please suggest me the right way to download the file from url using DownloadManager.
url:
http://-storage..net/95-****/95-3194.pdf?AWSAccessKeyId=T9YG9HWQC1LHE5G5VF38&Expires=1483443248&Signature=Z%2BkWzfEI2VawbCx%2F2Yto1kPcJKA%3D
Thanks
public void download(Uri uri) {
if (!isDownloading()) {
String fileName=getName(uri);
DownloadManager.Request request = new DownloadManager.Request(uri);
request.setTitle(fileName);
request.setNotificationVisibility(1);
request.allowScanningByMediaScanner();
request.addRequestHeader("Content-Type", "application/octet-stream");
request.addRequestHeader("Content-Disposition", "attachment; filename=\""+fileName.split("\\.")[0]+"."+fileName.split("\\.")[1].toUpperCase()+"\"");
String cookieContent = getCookieFromAppCookieManager(uri.getHost());
request.addRequestHeader("Cookie", cookieContent);
downloadId = downloadManager.enqueue(request);
register();
}
}
and below block returns the File name
private String getName(Uri uri) {
String name=uri.toString().split("jabord/")[1].split("\\?")[0];
return name;
}
returns the appcookie manager
public String getCookieFromAppCookieManager(String url) {
android.webkit.CookieManager cookieManager = android.webkit.CookieManager.getInstance();
if (cookieManager == null) {
return null;
}
String rawCookieHeader = null;
// Extract Set-Cookie header value from Android app CookieManager for this URL
rawCookieHeader = cookieManager.getCookie(url);
if (rawCookieHeader == null) {
return null;
}
return rawCookieHeader;
};
Please remove the headers and set the mimetype and then it will work. For example
public void download(Uri uri) {
if (!isDownloading()) {
String fileName=getName(uri);
DownloadManager.Request request = new DownloadManager.Request(uri);
request.setTitle(fileName);
request.setNotificationVisibility(1);
request.allowScanningByMediaScanner();
request.setMimeType("application/pdf");
Log.e("Extension with ","UpperCase-->"+"\""+fileName.split("\\.")[0]+"."+fileName.split("\\.")[1].toUpperCase()+"\"");
downloadId = downloadManager.enqueue(request);
register();
}
}
I was also facing the same issue. I solved it by removing the cookies.

Android: download arrow doesn't appear

i'm trying to develop an app that shows video and you can download it on your mobile
the app is working perfectly, but my problem is that the download arrow doesn't appear in notification bar.
I'm using download manager class.
Here's my method:
public void downloadFileFromUrl(String url, String fileName, DownloadManager downloadManager) {
String filePath=Environment.getExternalStorageDirectory() + File.separator + "BlueNet";
try {
Uri downloadUri = Uri.parse(url);
DownloadManager.Request request = new DownloadManager.Request(downloadUri);
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);
request.setDestinationInExternalPublicDir("/BlueNet",fileName);
request.setNotificationVisibility(
DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setVisibleInDownloadsUi(true);
request.allowScanningByMediaScanner();
idDwnldMng= downloadManager.enqueue(request);
}
catch (Exception ex){
Toast.makeText(this, ex.toString(), Toast.LENGTH_LONG).show();
}
}
Can someone help me?
Seems like you missing the permission:
<uses-permission
android:name="WRITE_EXTERNAL_STORAGE" />

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

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

WebView Direct Download returns HTML which use the original file extension

I am trying to perform a direct download inside the WebView, not linking to the browser.
webview.setDownloadListener(new DownloadListener() {
#SuppressLint("DefaultLocale")
#Override
public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
MimeTypeMap mtm = MimeTypeMap.getSingleton();
DownloadManager downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
Uri downloadUri = Uri.parse(url);
// get file name. if filename exists in contentDisposition, use it. otherwise, use the last part of the url.
String fileName = downloadUri.getLastPathSegment();
int pos = 0;
if ((pos = contentDisposition.toLowerCase().lastIndexOf("filename=")) >= 0) {
fileName = contentDisposition.substring(pos + 9);
pos = fileName.lastIndexOf(";");
if (pos > 0) {
fileName = fileName.substring(0, pos - 1);
}
}
// predict MIME Type
String fileExtension = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()).toLowerCase();
String mimeType = mtm.getMimeTypeFromExtension(fileExtension);
// request saving in Download directory
Request request = new DownloadManager.Request(downloadUri);
request.setTitle(fileName);
request.setDescription(url);
request.setMimeType(mimeType);
request.setDestinationInExternalPublicDir( Environment.DIRECTORY_DOWNLOADS, fileName);
Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_DOWNLOADS).mkdirs();
// request in download manager
downloadManager.enqueue(request);
}
});
And to open it,
// download complete toast
private BroadcastReceiver completeReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Resources res = context.getResources();
// make toast
Toast.makeText(context, res.getString(R.string.download_complete), Toast.LENGTH_SHORT).show();
// go to download finished window
startActivity(new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS));
}
};
#Override
protected void onPause() {
super.onPause();
// if app stops, stop reciever
unregisterReceiver(completeReceiver);
}
#Override
protected void onResume() {
// app start, start reciever
IntentFilter completeFilter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
registerReceiver(completeReceiver, completeFilter);
super.onResume();
}
}
However, the result is not the original file, but the HTML format of the source using the original file extension; e.g. it uses .pdf, but is a HTML file.
What is causing this problem, and How can I fix it?
Files I get
First of all, it is impossible to open with a normal PDF viewer, and when I don't open it as PDF, I get a normal HTML document:
<!DOCTYPE html>
<html>
…
</html>
There is NOTHING SPECIAL in the HTML document.
I found that your filename is coming with quote so just replace it.
fileName=fileName.replaceAll("\"", "");
you will get the proper file. I have also used that code in mine and it's successfully worked.

Categories

Resources