I am using DownloadManager to download a xml file from a URL. It works fine but I have two questions:
1.) How can I show a message about the download in the closed notification bar? I can show a message when I open the bar like shown in this snapshot:
2.) How can I programmatically remove tis notification?
My code for the DownloadManager:
//Download XML file from URL
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(URL));
request.setTitle("Download von "+Name+".xml");
request.setDescription("Download von "+Name+".xml");
// 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(FileSeperator+"XML"+FileSeperator, Name + FileExtension);
// get download service and enqueue file
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);
The DownloadManager API provides a remove(long... ids) method that lets you delete the downloaded file from the filesystem. remove() deletes the file from both the filesystem and the Download Manager app's list of downloaded files. It also removes the progress notification from the system notification drawer. Just pass it the ID you received when you enqueued your request.
What might be a bit surprising is that there may also be a completion notification, and if your download completes successfully, DownloadManager does not delete the completion notification, even if you call remove() with your download request ID.
Even if the user deletes the file from the Download Manager app, it will also remove only the progress notification from the system notification drawer, but the completion notification still persists. And if the user has removed the app manually, or if you have removed the download programmatically (via remove()), then the notification causes a crash in the OS, with a report of "Unfortunately, the process android.process.media has stopped." This seems to be an Android bug.
Even the NotificationManager API doesn't help because DownloadManager owns the completion notification, not your app. So cancelAll() won't have any effect.
Bottom line: if you don't want the completion notification, don't call setNotificationVisibility() on your request with the value VISIBILITY_VISIBLE_NOTIFY_COMPLETED. The default visibility is VISIBILITY_VISIBLE, which only displays the progress notification. And as I've described, that progress notification goes away automatically.
If you want total control over notifications, you can set your request to use VISIBILITY_HIDDEN (which requires the permission android.permission.DOWNLOAD_WITHOUT_NOTIFICATION). And then you can display whatever custom notifications you'd like in the usual way with the NotificationManager API.
For my app, where I'm downloading a jar file and then extracting its contents and removing the jar file, I settled on VISIBILITY_VISIBLE (with no completion notification). Here's how I create the request:
Request request = new Request(baseUrl + destinationFile))
.setDescription("file description")
.setDestinationInExternalFilesDir(mContext, null, destinationFile)
.setNotificationVisibility(Request.VISIBILITY_VISIBLE)
.setVisibleInDownloadsUi(true)
.setTitle("My App Title");
Yes, you can show a notification when the download is complete. You can remove it too. Follow this post How can I programmatically open/close notifications in Android?
You can use following function at onReceive method of broadcastReceiver
downloadManager.addCompletedDownload(YOUR_TITLE, YOUR_DESCRIPTION, true, YOUR_MIMETYPE, downloadedFile.getPath(), downloadedFile.getTotalSpace(), false);
BroadcastReceiver like this:
registerReceiver(broadcastReceiver, new IntentFilter("android.intent.action.DOWNLOAD_COMPLETE"));
If you set the last parameter to "true" the notification will be shown if download is complete.
If set to "false" the notification is only displayed while downloading and if download is complete and notification is canceled automatically
Notification overview. Method notify. Method cancel.
Related
I have an application where i have a feature to download a file already stored in firebase. i have implemented the code to download using download manager and at the same time show the user the notification of downloading that file but for some reason it is not working.
This is my code
val downloadRequest = DownloadManager.Request(Uri.parse(model.document.substringBeforeLast(".")))
downloadRequest.setTitle("الملف")
downloadRequest.setDescription("تحميل الملف")
downloadRequest.setVisibleInDownloadsUi(true)
downloadRequest.setDestinationUri(uri.toUri())
downloadRequest.allowScanningByMediaScanner()
downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
downloadManager.enqueue(downloadRequest)
Is the file getting downloaded but notification is not visible or file is not getting downloaded either?
try this and let me know if it still doesn't work :)
downloadRequest.setNotificationVisibility(
DownloadManager.Request.VISIBILITY_VISIBLE
)
EDIT
it seems that the last time I used it there was a difference in the destination that you are specifying.
val directory: File = File(Environment.getExternalStorageDirectory().path + "/myFile")
if(!directory.exists()) {
directory.mkdir()
}
...
downloadRequest.setDestinationInExternalPublicDir("/myFile","android")
Based on another SO answer, I am using the following lines of code to download media files:
DownloadManager.Request r = new DownloadManager.Request(Uri.parse(uri));
// This put the download in the same Download dir the browser uses
r.setDestinationInExternalPublicDir(Environment.DIRECTORY_PODCASTS, fileName);
// When downloading music and videos they will be listed in the player
// (Seems to be available since Honeycomb only)
r.allowScanningByMediaScanner();
// Notify user when download is completed
// (Seems to be available since Honeycomb only)
r.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
// Start download
DownloadManager dm = (DownloadManager) getActivity().getSystemService(Context.DOWNLOAD_SERVICE);
dm.enqueue(r);
Now, that is all good except that I have a few questions:
The person who answered said that the notifications can be customized. How can that be done?
If I want to add a "cancel" button to cancel the download and delete the file, how do I do it? What do I need to implement to get this behavior? :)
// Changing the Notification Title, Description, and its Visibility
DownloadManager mgr = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
Uri uri = Uri.parse("///.mp3");
DownloadManager.Request req = DownloadManager.Request(uri);
req.setTitle("Download");
req.setDescription("Kick Ass Description");
req.setVisibility(Request.VISIBILITY_VISIBLE_COMPLETION_ONLY);
Pretty self-explanatory.
My app has 5 big text files on them, each one about 40kb. Those files are updated weekly on a website.
I managed to set downloadManager to download the 5 files from the site. The problem is that I don't want the user to be able to use the app while the files are downloading because that will cause problems.
I want that when the user clicks the "Update" button it will show up a loading box. Then when the files finish downloading the box will disappear and a toast will say "Updated."
This is the method I've set up:
#SuppressLint("NewApi")
public void DownloadTxtFile(String url, String fileName) {
if (!new File(Environment.getExternalStorageDirectory()
+ "/folder").exists()) {
new File(Environment.getExternalStorageDirectory()
+ "/Dovahzul_Dictionary").mkdirs();
}
File file = new File(extStore.getAbsolutePath()
+ "/folder/" + fileName);
DownloadManager.Request request = new DownloadManager.Request(
Uri.parse(url));
request.setDescription("Downloading Text Files...");
request.setTitle("Updating")
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
}
request.setDestinationInExternalPublicDir("/Dovahzul_Dictionary",
fileName);
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
if (file.exists()) {
file.delete();
} else {
}
manager.enqueue(request);
}
By the way, if you find any problem with the method, plase inform me as well.
Thanks in advance.
I know this is old, but to anyone that has the same problem: What you need to do, is start the download in a different thread.
As android is not thread prof, you need to use AsyncTask instead. An AsyncTask is very similar to a thread. By starting and using one, you can do some quite long operations without freezing the ui. (Note that AsyncTasks are recomended for operations that take seconds, not minutes. In that case, you need to find something else)
You start an AsyncTask, and make it download the file. The problem is that AsyncTasks can't access ui methods, so they can't change threads.
You can, luckly, override a method they have to update the ui, and call it directly from it's onExecute.
Many tutorials on this can be found in the web.
I am trying to download file using Android Download Manager. As per docs:
The download manager will conduct the download in the background, taking care of HTTP interactions and retrying downloads after failures or across connectivity changes and system reboots.
But, download manager never resumes download, after network connection is restored(At least, in my case). I even tried with setting the request header, using addRequestHeader(). But nothing worked. My code is as follows:
Request request = new Request(Uri.parse(BASE_URL));
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI
| DownloadManager.Request.NETWORK_MOBILE);
request.setAllowedOverRoaming(false);
request.setTitle("Aarti Sangrah.zip");
request.setDestinationInExternalPublicDir(
Environment.DIRECTORY_DOWNLOADS, "Aarti Sangrah.zip");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
request.setNotificationVisibility(Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
} else {
request.setShowRunningNotification(true);
}
if (isResuming) {
request.addRequestHeader("Range", "bytes="
+ file.length());
}
enqueue = dm.enqueue(request);
In the docs, I couldn't found any method for resuming downloads. Also, I have a BroadcastReceiver for monitoring network changes.
I'm trying to set an icon for the DownloadManager request that I created, but I can't manage to do that.
I read about creating a BroadcastReceiver, but I was wondering if it's possible to do that without it.
This is my code for the DownloadManager Request:
final String filename = getIntent().getExtras().getString("id") + ".apk";
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setTitle(filename);
request.setDescription("Downloading...");
request.setMimeType("application/vnd.android.package-archive");
// 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("/Library", filename);
// get download service and enqueue file
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);
Toast.makeText(LinkActivity.this, "Download has started.", Toast.LENGTH_LONG).show();
Here's an example of what it looks like now:
My target is to change the image of the notification ImageView on the left.
Thank you very much.
You cannot override this icon. And, if I remember correctly, it would make no much sense to be able to, as download manager can have more than one downloading running and it will still take one notification slot to indicate that...