Android plus progress bar and progress text multi-threaded breakpoint Continuation download

Source: Internet
Author: User

We're going to use the progress bar first to change its style, to become a horizontal

<progressbar
Android:id= "@+id/pro"
Android:layout_width= "Match_parent"
android:layout_height= "Wrap_content"
Style= "@android: Style/widget.progressbar.horizontal"
/>

Update progress bar does not require handle

Then we have to set the progress bar in three places, first of all the length of the first request to set the maximum value of the progress bar Pro.setmax (length);

Then at the time of downloading, add up each progress, then set the current progress pro.setprogress (progress);

Finally to implement the breakpoint continued to read the progress file in the time set progress, in order to be broken after the progress bar can be updated;

Text progress bar to be implemented with TextView, update it will need to use handle to update the

 PackageCom.example.threaddownload;ImportJava.io.BufferedReader;ImportJava.io.File;ImportJava.io.FileInputStream;ImportJava.io.InputStream;ImportJava.io.InputStreamReader;ImportJava.io.RandomAccessFile;Importjava.net.HttpURLConnection;ImportJava.net.URL;ImportAndroid.os.Bundle;Importandroid.os.Environment;ImportAndroid.os.Handler;Importandroid.app.Activity;ImportAndroid.view.View;ImportAndroid.view.View.OnClickListener;ImportAndroid.widget.ProgressBar;ImportAndroid.widget.TextView; Public classMainactivityextendsActivity {Private StaticString Path = "Http://192.168.21.1:8080/ok/TGPSetup.exe"; Private Static intThreadCount = 3; Private Static intFinishthread = 0; //Add a progress bar    PrivateProgressBar Pro; //Number of Progress    Private intprogress; //Add text Progress    PrivateTextView TV; PrivateHandler Handler =NewHandler () { Public voidhandlemessage (android.os.Message msg) {//if there are times when the file is downloaded, a negative number is changed to long.Tv.settext ((Long) pro.getprogress () *100/pro.getmax () + "%");    };    }; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_main); Pro=(ProgressBar) Findviewbyid (R.id.pro); TV=(TextView) Findviewbyid (r.id.tv); Findviewbyid (R.id.start). Setonclicklistener (NewOnclicklistener () {@Override Public voidOnClick (View v) {NewThread () {@Override Public voidrun () {Try{URL URL=NewURL (path); HttpURLConnection Conn=(httpurlconnection) URL. OpenConnection (); Conn.setrequestmethod ("GET"); Conn.setreadtimeout (5000); Conn.setconnecttimeout (5000); if(Conn.getresponsecode () = = 200) {                                //the length of the first request to download                                intLength =conn.getcontentlength ();                                Pro.setmax (length); //send a message to the main threadHandler.sendemptymessage (1); //The file name should be truncated from the stringFile File =NewFile (Environment.getexternalstoragedirectory (), "TGPSetup.exe"); //generate temporary files before downloading, occupying a locationRandomaccessfile RDM =Newrandomaccessfile (file,"RWD"); //to the temporary file sizerdm.setlength (length); //CloseRdm.close (); //calculate the length that each thread should download                                intSize = length/ThreadCount; //assign start and end locations for each thread                                 for(inti = 0; i < ThreadCount; i++) {                                    intstart = i *size; intEnd = (i + 1) * size-1; //the end position of the last thread is the total length                                    if(i = = ThreadCount-1) {End=length; }                                    //each time a new thread is called                                    NewDownthread (Start, end, I). Start (); }                            }                        } Catch(Exception e) {//TODO auto-generated Catch blockE.printstacktrace ();            }}}.start ();    }        }); }    //Threads    classDownthreadextendsThread {Private intstart; Private intend; Private intthreadId;  PublicDownthread (intStartintEndintthreadId) {             This. Start =start;  This. end =end;  This. ThreadId =threadId; } @Override Public voidrun () {Try {                //Create a progress fileFile Progressfile =NewFile (Environment.getexternalstoragedirectory (), ThreadId + ". txt"); //Determine if there is a record of the progress of the file, if any, the start position is re-assigned value                if(Progressfile.exists ()) {FileInputStream fis=NewFileInputStream (Progressfile); BufferedReader BR=NewBufferedReader (NewInputStreamReader (FIS)); intLastprogress =Integer.parseint (Br.readline ()); Start+=lastprogress; //last downloaded display to progress barprogress+=lastprogress;                                        Pro.setprogress (progress);                Fis.close (); } System.out.println (ThreadId+ "Thread download Interval" + start + "---" +end); //Request Network againURL url =NewURL (path); HttpURLConnection Conn=(httpurlconnection) URL. OpenConnection (); Conn.setrequestmethod ("GET"); Conn.setreadtimeout (5000); Conn.setconnecttimeout (5000); //set the length of the file for this requestConn.setrequestproperty ("Range", "bytes=" + Start + "-" +end); //request part of the data is 206                if(Conn.getresponsecode () = = 206) {                    //the file input stream that gets the requested lengthInputStream is =Conn.getinputstream (); byte[] B =New byte[1024]; intLen = 0; //record the number of bytes downloaded each time                    intTotle = 0; //The file name should be truncated from the stringFile File =NewFile (Environment.getexternalstoragedirectory (), "TGPSetup.exe"); //the file that occupies the previous position, the equivalent of the output streamRandomaccessfile RDM =NewRandomaccessfile (file, "RWD"); //change the start position of the write fileRdm.seek (start);  while(len = Is.read (b))! =-1) {                        //every time the data in the stream is written to the temp file .Rdm.write (b, 0, Len); Totle+=Len; Progress+=Len; Handler.sendemptymessage (1);                        Pro.setprogress (progress); System.out.println (ThreadId+ "Threads" + "downloaded" +totle); //Save the total number of downloads in a progress fileRandomaccessfile RDM1 =Newrandomaccessfile (Progressfile,"RWD"); Rdm1.write ((Totle+ ""). GetBytes ());                    Rdm1.close ();                    } rdm.close (); Finishthread++; //download End Delete progress file                    if(Finishthread = =threadcount) {                        //Plus sync lock                        synchronized(path) { for(inti = 0; i < ThreadCount; i++) {File F=NewFile (Environment.getexternalstoragedirectory (), i + ". txt");                            F.delete (); } finishthread= 0; }                    }                }            } Catch(Exception e) {//TODO auto-generated Catch blockE.printstacktrace (); }        }    }}

Android plus progress bar and progress text multi-threaded breakpoint Continuation download

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.