Recently learned about some network requests in the Android environment, some of which are about network downloads. Here to analyze your own written demo, summarize what you have learned. For demo, follow some app download mall list add-ons in the ListView, then you can download and stop.
1. Overview
Here are a few of the more important classes Downloadmanager, Downloadservice, Downloadtask, Threaddaoimpl. The main download process is as follows.
(1) Downloadmanager is responsible for the deployment of download tasks, as well as the launch of the download service Downloadservice
(2) Downloadservice master gets some information about the downloaded file, including the name of the file, the length of the file, etc., and creates a download task Downloadtask
(3) Downloadtask is the official download of the file class, first check the database has not saved the corresponding breakpoint, and start from the corresponding breakpoint to download, if not the file fragment, and start the download
(4) Threaddaoimpl database operation class, mainly to save the breakpoint information downloaded by the thread
2. Multi-threaded breakpoints continue to pass
Of course, the most central part of this is the multi-threaded breakpoint continuation, the original is not very difficult, is to download the file into a plurality of parts, each part used by different threads simultaneously download.
2.1 Get download file length, set local file
In the Downloadservice setting the download file information, the following section of code:
classInitthread extends Thread {//FileInfo FileInfo;TaskInfo TaskInfo; PublicInitthread (TaskInfo taskinfo) { This. TaskInfo =TaskInfo; } @Override Public voidrun () {super.run (); LOG.I (Tag,"Initthread"); Try{URL URL=NewURL (Taskinfo.geturl ()); HttpURLConnection Con=(HttpURLConnection) url.openconnection (); Con.setrequestmethod ("GET"); Con.setconnecttimeout ( the); if(Con.getresponsecode () = =HTTPURLCONNECTION.HTTP_OK) { intLen = Con.getcontentlength (); <span style="color: #ff0000;">//total length of file </span>Taskinfo.setlenght (len); if(Len <=0) { return; } ............ Omit section here//Start settings Download file<span style="color: #ff6666;"> Randomaccessfile accessfile =NewRandomaccessfile (NewFile (Taskinfo.getfilepath (), Taskinfo.getfilename ()),"RWD"); Accessfile.setlength (len); //set file length </span>Accessfile.close (); //End Settings Download file....... Omit part}}Catch(malformedurlexception e) {e.printstacktrace (); } Catch(IOException e) {e.printstacktrace (); } } }
2.2 File Segmentation
The next work is a segmented download
For example, a 10M file, divided into three parts for the whole 10/3 = 3, the preceding one or two parts are 3M, the last one is 4M. So the first one from 0~2.9, the second from 3~5.9, and the third from 6~10, here is just a rough explanation. Next look at the code, in Downloadtask there are the following code:
/** * Start the download*/ Public voiddownlaod () {...... Omit section here//The start database does not have the corresponding thread information, then the corresponding thread information is created if(Threadinfolist.size () <=0) { <span style="color: #ff6666;">intblock = Mtaskinfo.getlenght ()/mthreadcount;//segment The download file, length of each segment </span> if(Block >0) { //start to create thread information based on the number of threads for(inti =0; I < mthreadcount;i++) {Threadinfo info=NewThreadinfo (I,mtaskinfo.geturl (), I*block, (i+1) *block-1,0); if(i = = Mthreadcount-1) { <span style="color: #ff0000;"> Info.setend (Mtaskinfo.getlenght ());//segment last, end position to end of file total length </span>} threadinfolist.add (info); //Join the listMthreaddao.insertthread (info);//inserting thread information into the database } //end establishes thread information based on the number of threads}Else{threadinfo Info=NewThreadinfo (0, Mtaskinfo.geturl (),0, Mtaskinfo.getlenght (),0); Threadinfolist.add (info); Mthreaddao.insertthread (info); } } //there is no corresponding thread information in the end database, the corresponding thread information is created....... Omit section here}
2.3 Download Threads
The following is the main download file for the thread
The main point is to set where to start reading and ending:
Con.setrequestproperty ("Range"threadinfo//Set the location to read the file, and the end position
Where local files are written:
Set where to start writing
/* * * Download Thread * */ class Downloadthread extends thread { ... The section @Override publicvoid run () {...) is omitted here. Omitted here section int// Read file location //start initialize download link ....... Omit section here
Con.setrequestproperty ("Range","bytes="+ Start +"-"+ threadinfo.getend ());//set the location of the read file, and the end location//End Initialize Download link//start initialization download to local file<span style="color: #ff0000;">accessfile =NewRandomaccessfile (NewFile (Mtaskinfo.getfilepath (), Mtaskinfo.getfilename ()),"RWD"); Accessfile.seek (start); //set where to start writing </span>//End initializes the downloaded file to the local....... Omit section here while(Readlen = inputstream.read (buffer))!=-1) { <span style="Background-color:rgb (255, 255, 255);"><span style="color: #ff0000;"> accessfile.write (buffer,0, Readlen);</span></span>//log.i (Tag, "Readlen =" + Readlen);Finished + =Readlen; Threadinfo.setfinished (finished); //set the download progress if(System.currenttimemillis ()-Time > -) {//log.i (Tag, "Readlen =" + Readlen);NotifyProgress (Threadinfo.getid (), finished);//notify download progress every 2 secondsTime =System.currenttimemillis (); } //start stop Download, save Progress if(ispause) {LOG.I (tag,"Pause name ="+mtaskinfo.getfilename ()); NotifyProgress (Threadinfo.getid (), finished); //Notify download ProgressMthreaddao.updatethread (Threadinfo.geturl (), Threadinfo.getid (), finished);//Update the thread information for the database return; } //end stop Download, save Progress } //end Read input stream write file....... Omit part}}Catch(malformedurlexception e) {e.printstacktrace (); } Catch(protocolexception e) {e.printstacktrace (); } Catch(IOException e) {e.printstacktrace (); }finally{....... Omit section here} super.run (); } }
2.4 Saving breakpoints
Storing breakpoint information in the Downloadthread download thread above is saved in the form of a database.
Mthreaddao. Updatethread (threadinfo. GETURL (),threadinfo//update database corresponding thread information
3 Other Auxiliary classes
(1) The database operation class Threaddaoimpl, the breakpoint information increases, changes, checks, deletes.
(2) Callback interface ondownload, download progress and download complete
(3) Download task Information TaskInfo
(4) Thread Information Threadinfo
4 thread pool
Thread pool management is used here because of the simultaneous download to multithreading. Create and initialize the thread pool in the Downloadservice class by multiplying the number of CPU cores by 2 plus 1 to set the amount
= Executors. Newfixedthreadpool (getnumberofcpucores//Initialize thread
Download with three threads at a time
Downloadtask (Downloadservice. this, info,mthreadpool//Set up a download task, 3 threads simultaneously download
Due to the limited number of threads in the thread Cheng, the idle thread will execute immediately after the download is started, and if not, wait until the download task is complete and then download.
Android Multi-threaded breakpoint continues to download multiple large files simultaneously