Recently researched multi-threaded download, wrote a demo, finishing down, may be helpful to others.
Multi-threaded download generally open two to three threads. If there are too many threads, time can be wasted on the thread switching, which is a waste of time. Too many threads is not a good thing.
The principle is to look at my other blog post, in fact, the code is ported to the Android system. Java implementation of multi-threaded download Demo
Public class mainactivity extends Activity { protected Static Final intDownload_error =1;Private Static Final intThread_error =2; Public Static Final intDwonload_finish =3;PrivateEditText Et_path;PrivateEditText Et_count;/** * Store the progress bar layout * / PrivateLinearLayout Ll_container;/** * The set of progress bars * / Privatelist<progressbar> PBS;/** * Android under the message processor, created in the main thread, can update the UI * / PrivateHandler Handler =NewHandler () { Public void Handlemessage(Message msg) {Switch(msg.what) { CaseDOWNLOAD_ERROR:Toast.makeText (Getapplicationcontext (),"Download Failed",0). Show (); Break; CaseTHREAD_ERROR:Toast.makeText (Getapplicationcontext (),"Download failed, please try again",0). Show (); Break; CaseDWONLOAD_FINISH:Toast.makeText (Getapplicationcontext (),"Download Complete",0). Show (); Break; } }; };/** * Number of threads * * Private intThreadCount =3;/** * Size of each download block * / Private LongBlockSize/** * Number of running threads * / Private intRunningthreadcount;@Override protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate); Setcontentview (R.layout.activity_main); Et_path = (EditText) Findviewbyid (R.ID.ET_ADDR); Et_count = (EditText) Findviewbyid (r.id.et_num); Ll_container = (linearlayout) Findviewbyid (R.ID.LL_PB); } Public void Download(View view) {//path to download files FinalString path = Et_path.gettext (). toString (). Trim ();if(Textutils.isempty (path)) {Toast.maketext ( This,"Sorry the download path cannot be empty",0). Show ();return; } String Count = Et_count.gettext (). toString (). Trim ();if(Textutils.isempty (path)) {Toast.maketext ( This,"Sorry, the number of threads cannot be empty",0). Show ();return; } threadcount = Integer.parseint (count);//Erase the old progress barLl_container.removeallviews ();//Add count of progress bars to the interfacePBS =NewArraylist<progressbar> (); for(intj=0; j<threadcount;j++) {ProgressBar PB = (ProgressBar) view.inflate ( This, R.LAYOUT.PB,NULL); Ll_container.addview (PB); Pbs.add (PB); } toast.maketext ( This,"Start Download",0). Show ();NewThread () { Public void Run() {Try{URL url =NewURL (path); HttpURLConnection conn = (httpurlconnection) url.openconnection (); Conn.setrequestmethod ("GET"); Conn.setconnecttimeout ( the);intCode = Conn.getresponsecode ();if(Code = = $) {LongSize = Conn.getcontentlength ();//Get the size of the file returned by the serverSystem.out.println ("Size of server file:"+ size); BlockSize = Size/threadcount;//1. First create a local blank file that is identical in size to the server. File File =NewFile (Environment.getexternalstoragedirectory (), GetFileName (path)); Randomaccessfile RAF =NewRandomaccessfile (file,"RW"); Raf.setlength (size);//2. Open several sub-threads to download the corresponding resources separately. Runningthreadcount = ThreadCount; for(inti =1; I <= threadcount; i++) {LongStartIndex = (I-1) * BLOCKSIZE;LongEndIndex = i * blocksize-1;if(i = = ThreadCount) {//Last threadEndIndex = Size-1; } System.out.println ("Open thread:"+ i +"Download location:"+ StartIndex +"~"+ EndIndex);intThreadsize = (int) (Endindex-startindex); Pbs.get (I-1). Setmax (Threadsize);NewDownloadthread (path, I, StartIndex, EndIndex). Start (); }} conn.disconnect (); }Catch(Exception e) {E.printstacktrace (); Message msg = Message.obtain (); Msg.what = Download_error; Handler.sendmessage (msg); } }; }.start (); }Private class downloadthread extends Thread { Private intThreadId;Private LongStartIndex;Private LongEndIndex;PrivateString path; Public Downloadthread(String Path,intThreadId,LongStartIndex,LongEndIndex) { This. Path = path; This. threadId = ThreadId; This. StartIndex = StartIndex; This. EndIndex = EndIndex; }@Override Public void Run() {Try{//When the total size of the front-thread download intTotal =0; File Positionfile =NewFile (Environment.getexternalstoragedirectory (), GetFileName (path) +threadid +". txt"); URL url =NewURL (path); HttpURLConnection conn = (httpurlconnection) URL. OpenConnection (); Conn.setrequestmethod ("GET");//Then continue downloading data from the last location if(Positionfile.exists () && positionfile.length () >0) {//Determine if there is a recordFileInputStream FIS =NewFileInputStream (Positionfile); BufferedReader br =NewBufferedReader (NewInputStreamReader (FIS));//Gets the total size of the last download of the current threadString lasttotalstr = Br.readline ();intLasttotal = integer.valueof (LASTTOTALSTR); System.out.println ("Last Thread"+ ThreadId +"Total size of downloads:"+ lasttotal); StartIndex + = Lasttotal; Total + = Lasttotal;//plus the total size of the last download. Fis.close ();//Storage database. //_id path ThreadID Total} conn.setrequestproperty ("Range","bytes="+ StartIndex +"-"+ EndIndex); Conn.setconnecttimeout ( the);intCode = Conn.getresponsecode (); System.out.println ("Code="+ code); InputStream is = Conn.getinputstream (); File File =NewFile (Environment.getexternalstoragedirectory (), GetFileName (path)); Randomaccessfile RAF =NewRandomaccessfile (file,"RW");//Specify where the file begins to write. Raf.seek (StartIndex); System.out.println ("section"+ ThreadId +"Threads: Where to start writing files:"+ string.valueof (startIndex));intLen =0;byte[] buffer =New byte[1024x768]; while(len = is.read (buffer))! =-1) {Randomaccessfile RF =NewRandomaccessfile (Positionfile,"RWD"); Raf.write (Buffer,0, Len); Total + = Len; Rf.write (string.valueof (total) getBytes ()); Rf.close (); Pbs.get (threadid-1). setprogress (total); } is.close (); Raf.close (); }Catch(Exception e) {E.printstacktrace (); Message msg = Message.obtain (); Msg.what = Thread_error; Handler.sendmessage (msg); }finally{//You can delete a record file only after all the threads have been downloaded. synchronized(Mainactivity.class) {System.out.println ("Threads"+ ThreadId +"Download complete."); runningthreadcount--;if(Runningthreadcount <1) {System.out.println ("All the threads have finished working." Delete files for temporary records "); for(inti =1; I <= threadcount; i++) {File F =NewFile (Environment.getexternalstoragedirectory (), GetFileName (path) + i +". txt"); System.out.println (F.delete ()); } Message msg = Message.obtain (); Msg.what = Dwonload_finish; Handler.sendmessage (msg); } } } } }PrivateStringGetFileName(String Path) {intStart = Path.lastindexof ("/")+1;returnPath.substring (start); }}
The Android system requires access to the network and access to the local memory card. Such as:
The source code has been uploaded to the csdn:http://download.csdn.net/detail/rootusers/8508137
Multi-threaded breakpoint download implementation under Android system