A recent study of multi-threaded download, wrote a demo. It may help others to sort it out.
Multi-threaded download generally open two to three threads. It's a waste of time to assume that too many threads will waste time on thread switching. Too many threads is not a good thing.
The principle of the words to see my also a 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 on the main thread. Ability to update 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 (),"Complete Download",0). Show (); Break; } }; };/** * Number of threads * * Private intThreadCount =3;/** * Size of each download block */ Private LongBlockSize/** * Number of threads being executed * / 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 the server file:"+ size); BlockSize = Size/threadcount;//1. First create a local blank file that is exactly the same size as 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) {//Infer 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 the location where the file starts 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{//Only if all the threads are finished downloading can be enough to delete the log files. synchronized(Mainactivity.class) {System.out.println ("Threads"+ ThreadId +"Finished downloading"); runningthreadcount--;if(Runningthreadcount <1) {System.out.println ("All the threads are working.
Delete files that are temporarily logged "); 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); }}
You need to add access to the network and access the local memory card permissions under the Android system. For example, with:
The source code has been uploaded to the csdn:http://download.csdn.net/detail/rootusers/8508137.
Multi-threaded breakpoint download implementation under Android system