Android Breakpoint download detailed analysis II

Source: Internet
Author: User

Because a blog is not finished, this is followed by a blog post.

After writing the view in MVC, it is written that we need to consider the control layer, his task is to use multithreading in the background to implement the breakpoint download.

First look at the source:

public class filedownloader{/* tag, easy to debug */private static final String tag = "Filedownloader";/* Context */private Contextual cont ext;/* used for database operations */private fileservice fileservice;/* stop Download */private boolean exit;/* downloaded file length */private int downloadsize = 0;/* Original file length */private int fileSize = 0;/* threads */private downloadthread[] threads;/* save files locally */private file savefile;/* cache lines The length of the download is */private map<integer, integer> data = new Concurrenthashmap<integer, integer> ();/* length of download per thread */ private int block;/* Download path */private String downloadurl;/** * Gets the number of threads */public int getthreadsize () {return threads.length;} /** * Exit download */public void exit () {this.exit = true;} public Boolean getexit () {return this.exit;} /** * Get File Size * @return file size */public int getfilesize () {return fileSize;} /** * Cumulative Downloaded size * @param size */protected synchronized void append (int size) {downloadsize + = size;} /** * Update specified thread last downloaded location * @param threadId thread ID * @param pos last downloaded location */protected synchronized void update (int threadId, int pos ) {This.data.put (ThreadId, POS); This.fileService.update (This.downloadurl,threadid, POS);} /** * Build File Downloader * @param downloadurl Download path * @param filesavedir File Save directory * @param threadnum Download Threads */public filedownloader (Cont Ext context, String DownloadURL, File filesavedir, int threadnum) {try{this.context = Context;this.downloadurl = Downloadu Rl;fileservice = new Fileservice (this.context); URL url = new URL (this.downloadurl), if (!filesavedir.exists ()) filesavedir.mkdirs ();//No directory is created this.threads = new Downloadthread[threadnum]; HttpURLConnection conn = (httpurlconnection) url.openconnection (); Conn.setconnecttimeout (5 * 1000); Conn.setrequestmethod ("GET"); Conn.setdoinput (true); Conn.setrequestproperty ("Accept", "Image/gif, Image/jpeg, Image/pjpeg, Image/pjpeg, Application/x-shockwave-flash, Application/xaml+xml, Application/vnd.ms-xpsdocument, APPLICATION/X-MS-XBAP, Application/x-ms-application, Application/vnd.ms-excel, Application/vnd.ms-powerpoint, Application/msword, */* "); Conn.setrequestproperty (" Accept-language ","ZH-CN "), Conn.setrequestproperty (" Referer ", DownloadURL), Conn.setrequestproperty (" Charset "," UTF-8 "); Conn.setrequestproperty ("User-agent", "mozilla/4.0" (compatible; MSIE 8.0; Windows NT 5.2; trident/4.0;. NET CLR 1.1.4322;. NET CLR 2.0.50727;. NET CLR 3.0.04506.30;. NET CLR 3.0.4506.2152;. NET CLR 3.5.30729); c Onn.setrequestproperty ("Connection", "keep-alive");/* The function of the Connect () method first creates the object and then establishes the connection. After you create the object, you can specify various options (for example, Doinput and * usecaches) before you establish the connection. An error occurs when you connect and then set. Actions that can be made after the connection (for example, * getcontentlength) and, if necessary, the connection is implicitly performed. */conn.connect (); if (conn.getresponsecode () = =) {this.filesize = Conn.getcontentlength ();//Gets the total size of the file according to the response if ( This.filesize <= 0) throw new runtimeexception ("Unkown file Size"); String filename = getfilename (conn);//Gets the file name this.savefile = new file (filesavedir, filename);//Build Save File Map<integer, integer> logdata = Fileservice.getdata (DownloadURL);//Get Download record if (logdata.size () > 0) {//If there is a download record, It is important to put the length of the downloaded data for each thread into data//This step, for example, when the user exits the application for a certain reason,//Then when he enters the application again, he should start the download from the last unfinished place instead of downloading it from the beginning.For (Map.entry<integer, integer> entry:logdata.entrySet ()) Data.put (Entry.getkey (), Entry.getvalue ());} if (this.data.size () = = This.threads.length) {//below calculates the total length of data that the thread has downloaded for (int i = 0; i < this.threads.length; i++) {this.do Wnloadsize + = This.data.get (i + 1);}} Calculate the length of data downloaded per thread This.block = (this.filesize% this.threads.length) = = 0? this.filesize/this.threads.length:this.filesize/this.threads.length+ 1;} Else{throw New RuntimeException ("Server no Response");} catch (Exception e) {throw new RuntimeException ("Don t connection this URL");}} /** * Gets the filename */private String getfilename (httpurlconnection conn) {/* * with the suffix in the URL address as the file name, for example the URL is: http://192.162.1.1:8080/ Web/lenver.exe, * Then his name is lenver.exe */string filename = this.downloadUrl.substring (this.downloadUrl.lastIndexOf ('/') ) + 1); if (filename = = null| | ". Equals (Filename.trim ())) {//If the file name is not obtained for (int i = 0;; i++) {String mine = Conn.getheaderfield (i), if (mine = = null) break;/* * The name of the requested path is illegal Shih * Content-disposition can actually control user requestsWhen the resulting content is saved as a file, a default file name is provided, * The file is displayed directly on the browser or the File download dialog box pops up when accessed. */if ("Content-disposition". Equals (Conn.getheaderfieldkey (i). toLowerCase ())) {Matcher m = Pattern.compile (". * Filename= (. *) "). Matcher (Mine.tolowercase ()), if (M.find ()) return M.group (1);}} filename = uuid.randomuuid () + ". tmp";//The default is to take a filename}return filename; /** * Start Download file * * @param listener * Monitor the number of downloads changes, if you do not need to know the number of live downloads, you can set to NULL * @return downloaded file size * @throws Exception */ public int Download (Downloadprogresslistener listener) throws Exception{try{randomaccessfile Randout = new Randomaccessfile (This.savefile, "RW"); if (this.filesize > 0) randout.setlength (this.filesize); Randout.close (); URL url = new URL (this.downloadurl), if (this.data.size ()! = this.threads.length) {//If the previous download was not previously downloaded or the number of downloaded threads is not the same as the current number of threads, Here are three this.data.clear (); for (int i = 0; i < this.threads.length; i++) {this.data.put (i + 1, 0);//Initialize each thread with a downloaded data length of 0}this . downloadsize = 0;} for (int i = 0; i < this.threads.length; i++) {//Open thread for download int downlength = This.data.get (i + 1)///Remove the length of a thread download from the database if (Downlength < This.block && This.downloadsize < this.filesize) {//Determine if the thread has finished downloading, Otherwise continue to download this.threads[i] = new Downloadthread (this, url,this.savefile,this.block,this.data.get (i + 1), i + 1); this.threads [I].setpriority (7);//Set Priority This.threads[i].start ();//Start thread} Else{this.threads[i] = null;}} Fileservice.delete (This.downloadurl);//If there are download records, delete them and add Fileservice.save (This.downloadurl,this.data) again; Boolean notfinish = true;//Download Incomplete while (Notfinish)//This loop is critical, he is able to maintain his caller, that is, downloadtask this thread has been running, and can then continue to send messages to the UI thread { The loop determines whether all threads complete the download thread.sleep (Notfinish = false;//assumes that all threads download complete for (int i = 0; i < this.threads.length; i++) {if (thi S.threads[i]! = null&&!this.threads[i].isfinish ()) {//If the discovery thread is not finished downloading notfinish = true;//setting flag for download not completed if ( This.threads[i].getdownlength () = =-1) {//If download fails, re-download this.threads[i] = new Downloadthread (This,url,this.savefile, This.block,this.data.get (i + 1), i + 1); this.threads[i].setpriority (7); This.threads[i].start ();}}} if (listener ! = null) listener.ondownloadsize (this.downloadsize);//Notifies the currently downloaded data length}if (downloadsize = = this.filesize) Fileservice.delete (This.downloadurl);//Download complete Delete record} catch (Exception e) {throw new Exception ("File download Error");} return this.downloadsize;} /** * Get HTTP response header fields * * @param http * @return */public static map<string, string> Gethttpresponseheader (Httpurlconnec tion http) {map<string, string> header = new linkedhashmap<string, string> (); for (int i = 0;; i++) {String mine = Http.getheaderfield (i); if (mine = = null) break;header.put (Http.getheaderfieldkey (i), mine);} return header;}}

Where the Fileservice class is the operation of a database class, the next blog, that is, the database of various additions and deletions operations.

Key Code Analysis:

Where private map<integer, integer> data = new Concurrenthashmap<integer, integer> (); This parameter, His role is to read each thread from the database every time the value of the download time is stopped, and the record is deleted when the download is complete.

We have stored the location of the download file in the root directory of the SD card, we can see that we have the location of the SD card as a parameter into the Filedownloader, and then by obtaining the URL of the last ' \ ' string as the file name. The file name does not exist when the server gives us the default name, you can see GetName () that method.

Then, the download method in the Filedownlaoder is called in mainactivity, and you can see that he has opened three threads to complete the download function. Then you can see that each time you download the corresponding thread from the database to read the download has been downloaded length, and then go to the length he should be downloaded to compare, if the thread to complete the task, that is, the length of the read from the database is equal to the length of the download he should be downloaded, do not download, otherwise continue. Then there will be a loop, the default is the dead loop, and his role is not to go through 900 milliseconds to detect whether the download completed and whether the download failed, and send the latest download progress to the UI thread. You can set the sleep time to any value, but it is appropriate, because the user generally need to go through a certain period of time to see the download progress, we update the UI as soon as possible to give the user a better experience, but not too "frequent, because the number of times to execute too much lossy performance." You can look at the size of the files you download to measure, larger can be a little longer time to update the UI, but the small one quickly update the UI.

Then, Filedownloader is actually a class that controls the thread that actually downloads the file. The really downloaded class is downloadthread. The next blog will share his use with you.

Android Breakpoint download detailed analysis II

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.