"Turn" Pro Android Learning Note (75): HTTP Service (9): Downloadmanager

Source: Internet
Author: User

Directory (?) [-]

    1. Small example
    2. Save where to download file information settings and read
    3. View download status and cancel downloads

The article reproduced only for non-commercial nature, and can not be accompanied by virtual currency, points, registration and other conditions, reprint must indicate the source: http://blog.csdn.net/flowingflying/

The application sometimes needs to download a large file from the Web and save it locally, this procedure is standard, so the Downloadmanager class is introduced in Android2.3. Related studies can also refer to the Android Learning Note (46): Internet communications-File download.

Small example

Let's look at a small example, as shown in. Layout consists of a button and a TextView, TextView used to display information. After the user presses the Start button, the file is downloaded through download in the background and prompted in the notification bar to see the download progress. When the download is finished, information about the notification bar will also be cleared. The android system has a download manager downloads that can view the files downloaded through Downloadmanager.

The source program is as follows:

public class Downloadmrgactivity extends activity{
Private TextView TV = null;
PrivateDownloadmanager Manager= NULL;
PrivateLong Downloadid=-1;

protected void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.LAYOUT.DOWNLOAD_MRG);
TV = (TextView) Findviewbyid (r.id.tv);
}

//"1" obtains downloadmanager instance by acquiring Download_service's reference
protected void Onresume () {
Super.onresume ();
manager = (Downloadmanager) getsystemservice (download_service);
Showinfo ("Get Downloadmanager instance:" + manager);

}
//"2" request to Downloadmanager to download a picture
public void Dodownload (View v) {//press button to trigger android:onclick= "Dodoownload"
Showinfo ("Dodownload () is called");
/* "2.1" Setting request */
Downloadmanager.request dmreq = new Downloadmanager.request
(
Uri.parse ("http://ww1.sinaimg.cn/large/5cf79a90jw1ecy18vfwlrj20xc18gtgd.jpg"));
Dmreq.settitle(Getresources (). getString (R.string.download_manager));//down notification bar, display the title of the message
dmreq.setdescription("index finger big move"); Down the notification bar, showing the description of the message
dmreq.setallowednetworktypes (DownloadManager.Request.NETWORK_WIFI);The default is no limit, this example is set to allow only WiFi connection when downloaded, can also be set to Network_mobile
/* "2.2" Downloadmanager after the background download completes, will broadcast the notification, set up the notification receiver: first set the filter condition, then register receiver */
Intentfilter filter = new Intentfilter (downloadmanager.action_download_complete);
Registerreceiver (myreceiver, filter);
/* "2.3" submits the request to the Downloadmanager and obtains the ID, which is used for processing the requested request */
Downloadid = Manager.enqueue (dmreq);

Showinfo ("Downloadid =" + Downloadid);
}
/ * "2.2.1" set Downloadmanager broadcast receiver */
Public Broadcastreceiver myreceiver = new Broadcastreceiver () {
Gets the ID number, which can be used to determine which request was completed. Intent has previously learned that it can be used to evoke component and deliver information component including activity, service, broadcast receiver, and content provider. The official broadcast receiver is here.
public voidOnReceive(context context, Intent Intent) {
Bundle extras = Intent.getextras ();
Long Donedownloadid = Extras.getlong (downloadmanager.extra_download_id);

if (donedownloadid! = Downloadid)
Return
Showinfo ("Download with id" + Donedownloadid + "is finished.");
Showinfo ("Download file uri is" +Manager.geturifordownloadedfile (Donedownloadid));
}

};

//"3" corresponds to Onresume (), some emptying process, such as unregister receiver, no longer listens for Downloadmanager broadcast
protected void OnPause () {
Super.onpause ();
Unregisterreceiver (Myreceiver);
Manager = null;

Downloadid =-1;
}

private void Showinfo (String s) {
LOG.D ("Pro-wei", s);
Tv.settext (s + "\ n" + tv.gettext ());
}
}

Where is it saved? (Download file information settings and read)

At the beginning of Android 4.2, Manager.geturifordownloadedfile (ID) will return the scheme is content, small example return URI is content://downloads/my_downloads/ <id>, without giving the path, I looked for a long time without finding where the default is. Of course, with URIs, you can read them, for example:

InputStream input = Getcontentresolver (). Openinputstream (URI);

However, we still want to know the specific storage there, you can view the download file information in the following way, you can also query a lot of information, specifically, you can flip through the API reference.

Cursor C = manager.query (new Downloadmanager.query (). Setfilterbyid (donedownloadid));
if (c! = null) {
C.movetofirst ();
Showinfo (c.getstring (c.getcolumnindex (downloadmanager.column_local_filename)));
C.close ();
}

Should query, file in a secret place, no wonder not to turn out, Logcat as follows:

If you want the file to be placed in a place where the user is easy to find, you can specify the path in the request as follows:

Dmreq. Setdestinationinexternalpublicdir (Environment.directory_downloads, "fish.jpg");

After the path is specified, the URI gives the path to the file file:///mnt/sdcard/Download/fish.jpg. Of course, to operate correctly, we must apply for Write_external_storage permissions.

In fact, we do not need to know the file path or content URI, we can also read the file, we add a ImageView control in layout to display the downloaded picture, the relevant code is as follows:

try{
parcelfiledescriptor PFD = Manager.opendownloadedfile (Donedownloadid);
FileDescriptor filedescriptor = Pfd.getfiledescriptor ();
Bitmap Bitmap = Bitmapfactory.decodefiledescriptor (FileDescriptor);
Pfd.close ();
ImageView image = (ImageView) Findviewbyid (r.id.download_image);
Image.setimagebitmap (bitmap);
}catch (Exception e) {
E.printstacktrace ();
}

View download status and cancel downloads

Add a Cancel button in layout to trigger the Canceldownload () function to cancel the download. We first query the status of the download, if it has been completed, do not process, otherwise cancel the download.

public void Canceldownload (View v) {
if (Downloadid > 0) {
Cursor C = manager.query (new Downloadmanager.query (). Setfilterbyid (Downloadid));
if (c = = null)
Return
C.movetofirst ();
int state =C.getint (C.getcolumnindex (Downloadmanager.column_status));
if (state! =downloadmanager.status_failed&& state! =downloadmanager.status_successful){
Showinfo ("Download is not finished, CANCEL it.");
Manager.remove (downloadid);If the file has already been downloaded, the Remove command does not delete the file
Downloadid =-1;
}
C.close ();
}
}

The example code covered in this blog post can be downloaded in the Pro Android Learning: Http Service Small example.

RELATED Links: My Android development related articles

"Go" Pro Android Learning Note (75): HTTP Service (9): 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.