Android note 4--Multi-threaded breakpoint Continuation

Source: Internet
Author: User



Multi-threaded breakpoint continuation is extremely important on any platform, and this part of knowledge is very important. The usual, use a picture to introduce today's content.

If you can't see the picture, you can right-click the new window.



The principle is also very simple multithreading is to separate a file into different parts to allow multiple threads to download, the breakpoint continues to use a text record of the current download, and then start reading the text download value can be.


Just look at the code.

public class Mainactivity extends Activity {String path = "Http://192.168.15.77:8080/QQPlayer.exe"; int threadcount = 3; int finishedthreadcount = 0; int currentpbprogress;private ProgressBar pb;private TextView TV; Handler Handler = new Handler () {public void Handlemessage (Android.os.Message msg) {Tv.settext ((long) pb.getprogress () * 100/pb.getmax () + "%");}; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.activity_main);//progress bar is used to display the current download progress, the total number of bytes downloaded as progress, the total size of the target file as MAXPB = (ProgressBar) Findviewbyid (R.ID.PB); TV = (TextView) Findviewbyid (r.id.tv);} public void Click (View v) {Thread t = new Thread () {@Overridepublic void run () {try {URL url = new URL (path); HttpURLConnection conn = (httpurlconnection) url.openconnection (); Conn.setrequestmethod ("GET"); Conn.setconnecttimeout (8000); Conn.setreadtimeout (8000); if (conn.getresponsecode () = = 200) {//Get the total length of the file to be downloaded int length = Conn.getcontentlength ();//Generate a temporary file locally, the temporary file size is consistent with the target file size file= New File (Environment.getexternalstoragedirectory (), GetFileName (path)); Randomaccessfile RAF = new Randomaccessfile (file, "RWD"); raf.setlength (length); Raf.close ();// Set the overall progress of the progress bar to the total length of the target file Pb.setmax (length);//calculate the lengths of each thread to be downloaded int size = length/threadcount;//Calculates the start and end positions for each thread for (int i = 0; i < T Hreadcount; i++) {int startIndex = i * size;int EndIndex = (i + 1) * SIZE-1;IF (i = = threadCount-1) EndIndex = LENGTH-1;//SYSTEM.O UT.PRINTLN ("thread" + i + "Download interval is:" + StartIndex + "~" + endIndex); new Downloadthread (StartIndex, EndIndex, i). Start ();}} catch (Exception e) {//TODO auto-generated catch Blocke.printstacktrace ();}}; T.start ();} String GetFileName (string path) {int index = Path.lastindexof ("/"); return path.substring (index + 1);} Class Downloadthread extends Thread{int startindex;int endindex;int threadid;public downloadthread (int startIndex, int EndIndex, int threadId) {super (); this.startindex = Startindex;this.endindex = Endindex;this.threadid = threadId;} @Overridepublic void Run () {//Open childThe thread downloads the target file try {file fileprogess = new file (Environment.getexternalstoragedirectory (), ThreadId + ". txt"); int lasttotal = 0; Determine if the text temporary file exists if (fileprogess.exists ()) {FileInputStream FIS = new FileInputStream (fileprogess); BufferedReader br = new BufferedReader (new InputStreamReader (FIS));//Get on the progress of the download lasttotal = Integer.parseint ( Br.readline ());//Change the start location of the download, the data has been downloaded, do not go to request startindex + = Lasttotal;fis.close ();// Writes the total progress of the last download to the progress bar currentpbprogress + = lasttotal;pb.setprogress (currentpbprogress); handler.sendemptymessage (0);} SYSTEM.OUT.PRINTLN ("thread" + ThreadId + "The final download interval is:" + StartIndex + "~" + endIndex); URL url = new URL (path); HttpURLConnection conn = (httpurlconnection) url.openconnection (); Conn.setrequestmethod ("GET"); Conn.setconnecttimeout (8000); Conn.setreadtimeout (8000);//define the range of requested data Conn.setrequestproperty ("range", "bytes=" + StartIndex + "-" + EndIndex), if (conn.getresponsecode () = = 206) {//Stream data only startIndex to EndIndex interval, Does not contain all data for the target file InputStream is = Conn.getinputstream (); byte[] B = new Byte[1024];inT len;int total = lasttotal; File file= new file (Environment.getexternalstoragedirectory (), GetFileName (path)); Randomaccessfile RAF = new Randomaccessfile (file, "RWD");//change the starting position of writing data to the RAF Raf.seek (StartIndex); while (len = Is.read ( b))! =-1) {total + = Len; SYSTEM.OUT.PRINTLN ("Threads" + threadId + "bytes downloaded:" + total); Raf.write (b, 0, Len);//In order to complete the breakpoint continuation, while loop the progress of each download, are written in a text temp file randomaccessfile rafprogress = new Randomaccessfile (fileprogess, "RWD"); Rafprogress.write ((Total + ""). GetBytes ()); Rafprogress.close (); currentpbprogress + = len;//All threads each time a len-length byte is downloaded, it is written to the total progress of the progress bar pb.setprogress ( currentpbprogress); handler.sendemptymessage (0);} SYSTEM.OUT.PRINTLN ("thread" + threadId + "Download completed---------------------"), Raf.close () finishedthreadcount++;//Three threads all downloaded, To remove the text temp file synchronized (path) {if (Finishedthreadcount = = 3) {for (int i = 0; i < ThreadCount; i++) {File F = new file (En Vironment.getexternalstoragedirectory (), i + ". txt"), if (F.exists ()) F.delete ();} Finishedthreadcount = 0;}}} catch (Exception e) {//TODO auto-Generated catch Blocke.printstacktrace ();}}} 


Android note 4--Multi-threaded breakpoint Continuation

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.