Download files from Android--downloadmanager

Source: Internet
Author: User

I. Overview of the problem

In Android development, the ability to download files, such as app version updates, is often used. After API Level 9, the Android system provides us with the Downloadmanager class, which is a system service provided by Android, which we complete with the file download. The entire download process is left to the system and does not require too much processing.

From the API documentation, you can see that Downloadmanager contains two internal classes:

Downloadmanager.query: Mainly used for querying download information .

Downloadmanager.request: Used primarily to initiate a download request .

Second, the function realization

First let's look at Downloadmanager.request, which encapsulates all the information needed to download a request. Through the constructor we can initialize a request object, and the address of the downloaded file needs to be passed in when the object is constructed.

New Downloadmanager.request (Uri.parse (""));

After constructing the object, we can set some properties for the request:

  • Addrequestheader (String header,string value): Add HTTP header information for network download requests
  • Allowscanningbymediascanner (): Used to set whether this Mediascanner scan is allowed.
  • Setallowednetworktypes (int flags): Sets the type of network used for download, which can be downloaded by default on any network, with the following network constants: Network_bluetooth,network_mobile , Network_wifi.
  • Setallowedoverroaming (Boolean allowed): Used to set whether the roaming state can be downloaded
  • setnotificationvisibility (int visibility): To display notification information in the status bar when downloading
  • Settitle (charsequence): Set title information for notification
  • SetDescription (charsequence): Set message information for notification
  • Setdestinationinexternalfilesdir, Setdestinationinexternalpublicdir, Setdestinationuri and other methods to set the download file storage path, Note If the download file is stored in the default path, the file will be deleted in case of insufficient space, so it is necessary to set the file directory using the above method.

The code to create the request object is as follows:

Downloadmanager.request Request =NewDownloadmanager.request (Uri.parse ("http://gdown.baidu.com/data/wisegame/55dc62995fe9ba82/jinritoutiao_448.apk")); //set what network conditions to downloadrequest.setallowednetworktypes (Request.network_wifi); //set the notification bar titlerequest.setnotificationvisibility (request.visibility_visible); Request.settitle (Download); Request.setdescription ("Today's headlines are being downloaded"); Request.setallowedoverroaming (false); //set File storage directoryRequest.setdestinationinexternalfilesdir ( This, Environment.directory_downloads, "Mydown");

After obtaining the system service, call the Downloadmanager object's Enqueue method to download, this method returns a number to indicate this download task:

Downmanager = (Downloadmanager) Getsystemservice (context.download_service); ID= Downmanager.enqueue ( request);

If you want to cancel the download, you can call the Remove method to complete, which deletes the download task and the downloaded file at the same time:

Downmanager.remove (ID);

When the file download is complete, we often need to do after the operation, such as APK, how to display the installation directly, then how we listen to the file when the download is complete? Downloadmanager sends an action-Action_download_complete broadcast when the file is now complete, so we can process it by registering a broadcast receiver:

    Private classDownloadcompletereceiverextendsbroadcastreceiver{@Override Public voidOnReceive (Context context, Intent Intent) {if(Intent.getaction (). Equals (Downloadmanager.action_download_complete)) {Longid = Intent.getlongextra (downloadmanager.extra_download_id,-1); Toast.maketext (mainactivity. This, "No.:" +id+ "the download task has been completed! ", Toast.length_short). Show (); }Else if(Intent.getaction (). Equals (downloadmanager.action_notification_clicked)) {Toast.maketext (mainactivity.< /c5> This, "Don't be blind!!!" ", Toast.length_short). Show (); }        }    }

Downmanager will manage all of the current tasks, so how do we get this information? This is the time to use the Downmanager.query object, through which we can query all the download task information.

Setfilterbyid (Long ... ids): Query download task information based on task number

Setfilterbystatus (int flags): Download task based on download status query

  Here's how to use it:

Private voidQuerydowntask (Downloadmanager Downmanager,intstatus) {Downloadmanager.query Query=NewDownloadmanager.query ();        Query.setfilterbystatus (status); Cursor Cursor=downmanager.query (query);  while(Cursor.movetonext ()) {String Downid=cursor.getstring (Cursor.getcolumnindex (downloadmanager.column_id)); String title=cursor.getstring (Cursor.getcolumnindex (downloadmanager.column_title)); String Address=cursor.getstring (Cursor.getcolumnindex (Downloadmanager.column_local_uri)); //String statuss = cursor.getstring (Cursor.getcolumnindex (Downloadmanager.column_status));String size=cursor.getstring (Cursor.getcolumnindex (Downloadmanager.column_bytes_downloaded_so_far)); String Sizetotal=cursor.getstring (Cursor.getcolumnindex (downloadmanager.column_total_size_bytes)); Map<string, string> map =NewHashmap<string, string>(); Map.put ("Downid", Downid); Map.put ("Title", title); Map.put ("Address", address); Map.put ("Status", sizetotal+ ":" +size);  This. Data.add (map);    } cursor.close (); }

You can see what information you can view and see the column_* constant information under Downloadmanger.

Third, the source code download

Students who want to experience the effect of their own, you can download the original project , directly run the view!

Download files from Android--downloadmanager

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.