Multi-thread download in Android

Source: Internet
Author: User
Public class mainactivity extends activity {// declare the control // path and number of threads private edittext et_url, et_num; // progress bar public static progressbar pb_thread; // display progress operation private textview TV _pb; // The number of threads public static int threadnum = 3; // the size of each thread to download public int blocksize; public static int threadcount; // The number of // accessed pathpublic string path; public static Boolean flag = true; // record progress bar value public static int pb_count = 0; public static handler; public static final int textvalue = 1; public static int pb_num = 0; public static int size = 0; @ overrideprotected void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. activity_main); et_url = (edittext) findviewbyid (R. id. et_path); et_num = (edittext) findviewbyid (R. id. et_threadnum); pb_thread = (progressbar) findviewbyid (R. id. pb_down); TV _pb = (textview) findviewbyid (R. id. TV _pb); handler = new handler () {@ overridepublic void handlemessage (Message MSG) {super. handlemessage (MSG); Switch (MSG. what) {Case textvalue: system. out. println ("-----------------------" + mainactivity. pb_count + "//" + mainactivity. size); // change textviewpb_num = (mainactivity. pb_count * 100)/mainactivity. size; TV _pb.settext ("the current progress is +" + pb_num + "%"); break; default: Break ;}}}@ overridepublic Boolean oncreateoptionsmenu (menu) {// inflate the menu; this adds items to the action bar if it is present. // getmenuinflater (). inflate (R. menu. down, menu); Return true;} // download public void download (view v) {// change the variable value: mainactivity. flag = true; mainactivity. pb_count = 0; Path = et_url.gettext (). tostring (); string threadnum_et = et_num.gettext (). tostring (); If (textutils. isempty (PATH) | textutils. isempty (threadnum_et) {toast. maketext (this, "cannot be blank", toast. length_long ). show (); return;} toast. maketext (this, "url:" + path + "--" + threadnum_et, toast. length_long ). show (); // convert to the number threadnum = integer. valueof (threadnum_et); New thread (New runnable () {@ overridepublic void run () {try {// create a URL object url = new URL (PATH ); // create the httpurlconnection object httpurlconnection = (httpurlconnection) URL. openconnection (); // sets the method for sending a request to httpurlconnection. setrequestmethod ("get"); // sets whether the request has timed out. setconnecttimeout (5000); // sets httpurlconnection. setrequestproperty ("User-Agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)"); // whether the response is successful if (httpurlconnection. getresponsecode () = 200) {// get the file size = httpurlconnection. getcontentlength (); system. out. println ("file size" + size); // set the maximum value of the progress bar pb_thread.setmax (size ); // create a file // save it to the SD card. // first, determine whether sdcardif (environment. getexternalstoragestate (). equals (environment. media_mounted) {// get the sdcard file directory object file sdfile = environment. getexternalstoragedirectory (); // create a file object file = new file (sdfile, "youdao.exe"); randomaccessfile accessfile = new randomaccessfile (file, "RWD "); // set the file size accessfile. setlength (size); // the size of blocksize = size/threadnum downloaded by each thread; // enable three threads to operate the file for (INT I = 1; I <= threadnum; I ++) {// 1 2 3 // calculate the start position of each thread int startsize = (I-1) * blocksize; // The end position int endsize = (I) * blocksize; // if (I = threadnum) when the thread is the last thread {// determine whether the file size is greater than the calculated end position if (size> endsize) {// The end position is equal to the file size endsize = size;} // creates a random reading randomaccessfile threadaccessfile = new randomaccessfile (file, "RWD") for each thread "); new thread (New downloadthread (I, threadaccessfile, startsize, endsize, PATH )). start () ;}}} catch (malformedurlexception e) {// todo auto-generated catch blocke. printstacktrace ();} catch (ioexception e) {// todo auto-generated catch blocke. printstacktrace ();}}}). start () ;}// pause the public void downpause (view v) {toast. maketext (this, "Suspend", toast. length_long ). show (); this. flag = false ;}}

Public class downloadthread implements runnable {// encapsulation of the downloaded file public randomaccessfile accessfile; // the starting position of the file downloaded by the thread public int startsize; Public int endsize; // File Download path Public String path; Public int threadid; // The thread ID public downloadthread (INT threadid, randomaccessfile accessfile, int startsize, int endsize, string path) {This. threadid = threadid; this. accessfile = accessfile; this. startsize = startsize; thi S. endsize = endsize; this. path = path ;}@ overridepublic void run () {// execute the run method try {// create a file to the SD card // first determine whether sdcardif (environment. getexternalstoragestate (). equals (environment. media_mounted) {// get the sdcard file directory object file sdfile = environment. getexternalstoragedirectory (); file threadfile = new file (sdfile, threadid + ". TXT "); If (threadfile. exists () {// read the content of the file // create the input stream object of the file fileinputstream FS = new fileinpu Tstream (threadfile); // use the tool class to read byte data [] = streamtools. istodata (FCM); // convert it to string threadlen = new string (data); If (threadlen! = NULL )&&(! "". Equals (threadlen) {startsize = integer. valueof (threadlen); // solves the error of 416bug if (startsize> endsize) {startsize = endsize-1 ;}}} // create a file // create a URL object url = new URL (PATH); // create an httpurlconnection object httpurlconnection = (httpurlconnection) URL. openconnection (); // sets the request header httpurlconnection. setrequestmethod ("get"); // sets whether the request has timed out. setconnecttimeout (5000); // sets httpurlconnecti On. setrequestproperty ("User-Agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)"); // key settings httpurlconnection. setrequestproperty ("range", "bytes =" + startsize + "-" + endsize); // output the current thread system. out. println ("current thread" + threadid + "Download start position:" + startsize + "Download end position:" + endsize ); // response successful // set the start position of the random File Read accessfile. seek (startsize); // obtain the corresponding Stream object inputstream is = httpurlconnection. getinputstream (); // Create the output stream object byte buffer [] = new byte [1024]; int Len = 0; int threadtotal = 0; // Save the record/while (LEN = is. read (buffer ))! =-1) {accessfile. write (buffer, 0, Len); threadtotal + = Len; // record the length you write. // XML file // change the progress bar: setprogressbar (LEN ); // record the length of the downloaded file fileoutputstream Fos = new fileoutputstream (threadfile); FOS. write (threadtotal + ""). getbytes (); FOS. flush (); FOS. close (); // send the handler message mainactivity. handler. sendemptymessage (mainactivity. textvalue); If (! Mainactivity. flag) {return ;}} accessfile. close (); is. close (); system. out. println (threadid + "thread execution completed"); // thread operation synchronized (mainactivity. class) {mainactivity. threadcount ++; If (mainactivity. threadcount> = mainactivity. threadnum) {for (INT I = 1; I <= mainactivity. threadnum; I ++) {// obtain the file deletefile = new file (sdfile, I + ". TXT "); If (deletefile. exists () {// Delete deletefile. delete () ;}}}} catch (malformedurlexception e) {// todo auto-generated catch blocke. printstacktrace ();} catch (ioexception e) {// todo auto-generated catch blocke. printstacktrace () ;}} public synchronized void setprogressbar (INT Len) {mainactivity. pb_count + = Len; mainactivity. pb_thread.setprogress (mainactivity. pb_count );}}

Public class streamtools {public static byte [] istodata (inputstream is) throws ioexception {// bytearrayoutputstream BOPS = new bytearrayoutputstream (); // The cache for reading Data byte buffer [] = new byte [1024]; // The read length record int Len = 0; // read while cyclically (LEN = is. read (buffer ))! =-1) {BOPs. write (buffer, 0, Len);} // converts the read content to a byte array byte data [] = BOPs. tobytearray (); BOPs. flush (); BOPs. close (); is. close (); return data ;}}

Complete source code please visit: http://download.csdn.net/detail/chrp99/5616629

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.