A tutorial on using the Downloadmanager class to manage data downloads in Android _android

Source: Internet
Author: User
Tags unique id

Starting with the Android 2.3 (API level 9), Android uses system Services (service) to provide download Manager to optimize the processing of long time downloads. Download Manager handles HTTP connections and monitors the state changes in the connection and the system reboots to ensure that each download task completes successfully.
Using Download Manager is a good option in most cases involving downloads, especially when users switch to different applications and the download needs to continue in the background. And the very important situation where the current load is successfully completed (Downloadmanager support for the continuation of the breakpoint).

To use the download Manager, use the Getsystemservice method to request the Download_service service of the system, which is the following code fragment:

String servicestring = Context.download_service; 
Downloadmanager Downloadmanager; 
Downloadmanager = (Downloadmanager) getsystemservice (servicestring); 

Download files
to request a download operation, you need to create a Downloadmanager.request object that passes the URI of the file that will request the download to the Enqueue method of download manager, as shown in the following code fragment:

String servicestring = Context.download_service; 
Downloadmanager Downloadmanager; 
Downloadmanager = (Downloadmanager) getsystemservice (servicestring); 
Uri uri = uri.parse ("Http://developer.android.com/shareables/icon_templates-v4.0.zip"); 
Downloadmanager.request request = new request (URI); 
Long reference = Downloadmanager.enqueue (request); 

The reference variable returned here is a unique ID that the system assigns to the current download request, and we can then get this download task back, do something we want to do or query
The status of the download and cancel the download and so on.
We can add HTTP headers to the Downloadmanager.request object request through the Addrequestheader method, or you can override the MIME type returned from the server by using the Setmimetype method.
We can also specify what connection state to perform the download operation. Setallowednetworktypes method can be used to limit the download on WiFi or mobile network, setallowedoverroaming method
Can be used to prevent mobile phones from downloading in a roaming state.
The following code fragment specifies that a larger file can be downloaded only on WiFi:

Request.setallowednetworktypes (Request.network_wifi);

The Android API level 11 introduces the Getrecommendedmaxbytesovermobile class method (static method), returns the maximum number of recommended bytes under the current mobile network connection, and can be used to determine the download
should be limited to wifi conditions.
Once the Enqueue method is invoked, the download begins as soon as the data connection is available and download Manager is available.
To obtain a system notification (notification) when the download is complete, register a broadcast receiver to receive the Action_download_complete broadcast, which will contain a
The EXTRA_DOWNLOAD_ID information contains the ID of the download that has been completed in the intent, as shown in the code snippet below:

Intentfilter filter = new Intentfilter (downloadmanager.action_download_complete); 
Broadcastreceiver receiver = new Broadcastreceiver () { 
 @Override public 
 void OnReceive (context context, Intent Intent) { 
 Long reference = Intent.getlongextra (downloadmanager.extra_download_id,-1); 
 if (mydownloadreference = = reference) { 
Registerreceiver (receiver, filter); 

Using the Opendownloadedfile method of Download Manager, you can open a file that has already been downloaded and return a Parcelfiledescriptor object. We can query the saved address of the download file through Download Manager, if we have developed the path and filename when downloading, we can also manipulate the file directly.
We can register a broadcast recipient for the Action_notification_clicked action when the user clicks on a download item from the notification bar or clicks on a downloadable item from downloads app
, the system emits a broadcast that clicks on the download.
The code snippet is as follows:

Intentfilter filter = new Intentfilter (downloadmanager.action_notification_clicked); 
Broadcastreceiver receiver = new Broadcastreceiver () { 
 @Override public 
 void OnReceive (context context, Intent Intent) { 
 String extraid = downloadmanager.extra_notification_click_download_ids; 
 long[] References = Intent.getlongarrayextra (extraid); 
 for (long reference:references) 
  if (reference = = mydownloadreference) { 
  //do something with downloading file.
Registerreceiver (receiver, filter); 

Customizing the style of download Manager notifications
By default, the notification bar displays each download that is managed by Download Manager and each notification displays the current download progress and the name of the file.
With Download Manager, you can customize the notification style for each download request, including completely hiding notification. The following code fragment shows the use of the Settitle and setdescription
method to customize the text displayed in the file download notification.

Request.settitle ("earthquakes"); 
Request.setdescription ("Earthquake XML"); 

The Setnotificationvisibility method can be used to control when the notification is displayed, or even to hide the request's notification. There are several parameters:

    • Request.visibility_visible: In the download process, the notification bar will always display the download notification, when the download is complete, the notification will be removed, this is the default parameter value.
    • request.visibility_visible_notify_completed: In the download process, the notification bar will always display the download notification, after the download is complete the notification will continue to display until the user clicks on the
    • notification or eliminate the notification.
    • Request.visibility_visible_notify_only_completion: The notification will not be displayed until the download is complete.
    • Request.visibility_hidden: The notification for this download request is not displayed. If you want to use this parameter, you need to add Download_without_notification permissions to the application's manifest file.

Specify download Save Address

By default, all files downloaded through Download Manager are saved in a shared download cache, using system-generated file names each request object can develop a download
Saved addresses, in general, all downloads should be stored in the external store, so we need to add Write_external_storage permissions to the application manifest file:

<uses-permission android:name= "Android.permission.WRITE_EXTERNAL_STORAGE"/> 

The following code fragment is a method of specifying an arbitrary save location in an external store:

Request.setdestinationuri (Uri.fromfile (f)); 

F is a file object.
If the downloaded file is dedicated to your application, you may want to put the file in a proprietary folder that your application uses in external storage. Note that this folder does not provide access control,
So other applications can access this folder as well. In this case, if your application is uninstalled, then the folder will also be deleted.
The following code fragment is the way to specify that the path to a stored file is a private folder that is applied to an external store:

Request.setdestinationinexternalfilesdir (This, 
 environment.directory_downloads, "bugdroid.png"); 

If the downloaded file wants to be shared by other applications, especially if you download the files you want to be scanned by media scanner (such as music files), then you can specify your download path in
Under a public folder that is stored externally, the following code fragment is the way to store a file in a public music folder in an external store:

Request.setdestinationinexternalpublicdir (Environment.directory_music, 

By default, files downloaded via download Manager are not scanned by media scanner, and these downloaded files (music, videos, etc.) are not seen in applications such as gallery and music player.
In order for the downloaded music files to be scanned by other applications, we need to invoke the Allowscaningbymediascanner method of the Request object.
If we want the downloaded file to be scanned and managed by the downloads application of the system, we need to call the Setvisibleindownloadsui method of the request object and pass the argument true.

Canceling and deleting downloads
Download Manager's Remove method can be used to cancel a prepared download, abort an ongoing download, or delete a completed download.
The Remove method accepts several download IDs as parameters, and you can set one or several downloads that you want to cancel, as shown in the following code snippet:

Downloadmanager.remove (Reference_1, reference_2, reference_3); 
This method returns the number of downloads that were successfully canceled, if a download was canceled, all associated files, Partially downloaded files and fully downloaded files will be deleted.
query Download Manager
You can query download Manager to get the status, progress, and details of the download task. Returns a cursor that contains the details of the download task through the Query method. The
Query method passes a Downloadmanager.query object as a parameter, and the Downloadmanager.query object's Setfilterbyid method allows you to filter the ID of the download task that we want to query. You can also use the Setfilterbystatus method to filter the download task for one of the states we want to query, passing arguments that are downloadmanager.status_* constants, which can be specified as being in progress, paused, failed, and completed in four states.
Download Manager contains a series of column_* static string constants that you can use to query the result column indexes in cursor. We can query the various details of the download task, including status, file size, number of bytes already downloaded, title, description, URI, local filename and URI, media type, and Provider download URI.
The following code snippet queries the implementation of the local filename and URI of the download completion file by registering the broadcast recipient listening to the download completion event:

 @Override public void OnReceive (context context, Intent Intent) {Long reference = in 
 Tent.getlongextra (downloadmanager.extra_download_id,-1); 
 if (mydownloadreference = = Reference) {Query mydownloadquery = new query (); 
 Mydownloadquery.setfilterbyid (reference); 
 Cursor mydownload = Downloadmanager.query (mydownloadquery); 
  if (Mydownload.movetofirst ()) {int filenameidx = Mydownload.getcolumnindex (downloadmanager.column_local_filename); 
  int fileuriidx = Mydownload.getcolumnindex (Downloadmanager.column_local_uri); 
  String fileName = mydownload.getstring (FILENAMEIDX); 
  String Fileuri = mydownload.getstring (FILEURIIDX); 
  TODO do something with the file. 
 LOG.D (TAG, FileName + ":" + Fileuri); 
 } mydownload.close (); } 

For paused and failed downloads, we can query the Column_reason column to find out the reason of the integer digital.
for downloads of the status_paused state, you can translate the integer digital of the reason by downloadmanager.paused_* static constants to determine whether the download is paused because it waits for a network connection or waits for a WiFi connection or is ready to download three different reasons.
for status_failed state downloads, we can downloadmanager.error_* to determine the cause of the failure, possibly the error code (cause of failure) including no storage devices,
Low storage space, duplicate file names, or HTTP Errors
The following code is how to query for all currently paused download tasks, extract the reason for the pause and the file name, download the title, and implement the current progress:

Obtain the Download Manager Service. 
String servicestring = Context.download_service; 
Downloadmanager Downloadmanager; 
Downloadmanager = (Downloadmanager) getsystemservice (servicestring); 
Create a query for paused downloads. 
Query pauseddownloadquery = new query (); 
Pauseddownloadquery.setfilterbystatus (downloadmanager.status_paused); 
Query the Download Manager for paused downloads. 
Cursor pauseddownloads = Downloadmanager.query (pauseddownloadquery); 
Find the column indexes for the data we require. 
int reasonidx = Pauseddownloads.getcolumnindex (Downloadmanager.column_reason); 
int titleidx = Pauseddownloads.getcolumnindex (Downloadmanager.column_title);  
int filesizeidx = Pauseddownloads.getcolumnindex (downloadmanager.column_total_size_bytes); 
int bytesdlidx = Pauseddownloads.getcolumnindex (Downloadmanager.column_bytes_downloaded_so_far); 
Iterate over the result Cursor. while (Pauseddownloads.movetonext ()) {//Extract the data we require from THe Cursor. 
 String title = pauseddownloads.getstring (TITLEIDX); 
 int fileSize = Pauseddownloads.getint (FILESIZEIDX); 
 int bytesdl = Pauseddownloads.getint (BYTESDLIDX); 
 Translate The pause reason to friendly text. 
 int reason = Pauseddownloads.getint (REASONIDX); 
 String reasonstring = "Unknown"; 
 Switch (reason) {case DownloadManager.PAUSED_QUEUED_FOR_WIFI:reasonString = ' Waiting for WIFI '; Case DownloadManager.PAUSED_WAITING_FOR_NETWORK:reasonString = "Waiting for connectivity"; 
 Break Case DownloadManager.PAUSED_WAITING_TO_RETRY:reasonString = "waiting to retry"; 
 }//Construct a status summary StringBuilder sb = new StringBuilder (); 
 Sb.append (title). Append ("\ n"); 
 Sb.append (reasonstring). Append ("\ n"); 
 Sb.append ("downloaded"). Append (bytesdl). Append ("/"). Append (FileSize); 
Display the status log.d ("DOWNLOAD", sb.tostring ()); 
}//Close the result Cursor. 

 Pauseddownloads.close ();

attached: Some important functions and parameter finishing of Downloadmanager

The Downloadmanager class provides several ways to handle the
Long Enqueue (downloadmanager.request Request)//Save in queue a new download
Parcelfiledescriptor Opendownloadedfile (Long ID)//Open a downloaded file for reading, the long ID in the parameter is a record in a provider.
Cursor query (downloadmanager.query query)//Queries a download, returns a Cursor
int remove (long ... IDs)//Cancel the download at the same time remove these strips from the download management.
We can see that the methods provided are simpler and give us a way to add, query and remove the final encapsulation of our operations into a provider database, but for the details of querying and adding tasks, We're going to look at the Downloadmanager.request class and the Downloadmanager.query class.
I. Members and definitions of the Downloadmanager.request class

  • Downloadmanager.request Addrequestheader (string header, String value)//Add an HTTP request header, for these two parameters, the Android Development network gives you a small example, For example, the User-agent value can be Android123 or Windows XP, and so on, primarily to provide identity to the server.
  • Downloadmanager.request setallowednetworktypes (int flags)//Set the type of network allowed, this step Android 2.3 is doing well and there are currently two definitions of Network_ Mobile and Network_wifi we have the option to use a removable network or WiFi to download.
  • Downloadmanager.request setallowedoverroaming (Boolean allowed)//for downloads, consider whether roaming is allowed here, taking into account traffic charges.
  • Downloadmanager.request setdescription (charsequence description)//Set A descriptive information, mainly the final display of the notification hint, you can write your own difference
  • Downloadmanager.request Setdestinationinexternalfilesdir (context, String Dirtype, String subpath)// The set target is stored in an external directory, and the general location can be obtained by using the Getexternalfilesdir () method.
  • Downloadmanager.request Setdestinationinexternalpublicdir (String dirtype, String subpath)//Set the public directory for external storage, Generally obtained by Getexternalstoragepublicdirectory () method.
  • Downloadmanager.request Setdestinationuri (URI uri)//Set the URI that needs to download the target, can be HTTP, ftp and so on.
  • Downloadmanager.request Setmimetype (String mimetype)//Set MIME type, see server Configuration here, the general state of all is UTF-8 encoding.
  • Downloadmanager.request Setshowrunningnotification (Boolean show)//whether to display a hint of download progress
  • Downloadmanager.request Settitle (charsequence title)//Set notification title
  • Downloadmanager.request Setvisibleindownloadsui (Boolean isVisible)//setting whether the interface of the download management class is displayed during processing
  • Of course, Google also provides an easy way to instantiate this class, which is Downloadmanager.request (Uri Uri), and we simply fill in a URI, and the above setting uses the default.

Second, Downloadmanager.query class

For the state of the current download, we can use the Downloadmanager.query class to get it, and this class is simpler, offering only two methods.

    • Downloadmanager.query Setfilterbyid (Long ... IDs)//filter lookup based on ID.
    • Downloadmanager.query setfilterbystatus (int flags)//lookup according to the status of the task.

The detailed status is defined in the Android.app.DownloadManager class and is currently defined in Android 2.3 as:

    • int status_failed failed
    • int status_paused paused
    • int status_pending wait will begin
    • int status_running is in process
    • int status_successful has been downloaded successfully

Finally, the Android Development network reminds you that the query method provided by the Downloadmanager class returns a cursor object that is stored in the Column_status field of the cursor.

1. The completion of the download status is broadcast in the form of notification to everyone, the current API level of 9 defines the following three kinds of intent action
(1) Action_download_complete download complete the action.
(2) action_notification_clicked is triggered when a user clicks an item in NOTIFICATION to download the management.
(3) Action_view_downloads View Downloads
2. For an unfinished item, in cursor we look for the Column_reason field, which may have the following definition:
(1) Int error_cannot_resume cannot be continued for some other reason.
(2) int Error_device_not_found external storage device not found, such as SD card not plugged in.
(3) int error_file_already_exists The file you want to download already exists, Android123 prompts you to download an admin class that does not overwrite existing files, so if you need to download them again, delete the previous files first.
(1) int error_file_error may cause file errors due to the SD card.
(2) The int error_http_data_error has a problem in the HTTP transfer process.
(3) int error_insufficient_space due to insufficient space of SD card
(4) Int error_too_many_redirects This HTTP has too many redirects, resulting in the inability to download properly
(5) Int Error_unhandled_http_code cannot get the reason for HTTP error, for example, the remote server is not responding.
(6) Int Error_unknown unknown type of error.
3. For some states of a pause, the same value for the Column_reason field may be the following definition
(1) int paused_queued_for_wifi because of mobile network data problem, wait for WIFI connection can be used and then re-enter the download queue.
(2) int Paused_unknown unknown cause the task download paused.
(3) int paused_waiting_for_network may not be able to download because there is no network connection, waiting for available network connection recovery ...
(4) int paused_waiting_to_retry due to a lot of reasons caused the download paused, waiting for a retry.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.