Android_05 _ multi‑thread resumable download

Source: Internet
Author: User
Tags file url

Android_05 _ multi‑thread resumable download

MainActivity. java

 

Package com. itheima. mobilemultidownload; import java. io. bufferedReader; import java. io. file; import java. io. fileInputStream; import java. io. inputStream; import java. io. inputStreamReader; import java. io. randomAccessFile; import java.net. httpURLConnection; import java.net. URL; import android. OS. bundle; import android. OS. environment; import android. OS. handler; import android. app. activity; import android. view. menu; Import android. view. view; import android. widget. progressBar; import android. widget. textView; public class MainActivity extends Activity {static int ThreadCount = 3; static int finishedThread = 0; int currentProgress; String fileName = QQPlayer.exe; // confirm String path = http: // 192.168.13.13: 8080/+ fileName; private ProgressBar pb; TextView TV; Handler handler = new Handler () {public void handleMessage (android. o S. message msg) {// change the variable to long and calculate it in long. Otherwise, when the file is large, the text progress will be negative. setText (long) pb. getProgress () * 100/pb. getMax () + %) ;}}; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); pb = (ProgressBar) findViewById (R. id. pb); TV = (TextView) findViewById (R. id. TV);} public void click (View v) {Thread t = new Thread () {@ Overridepubli C void run () {// send a get request to request the resource try of this address {// this request is to get the file size, to set the size of the virtual temporary file URL = new url (path); HttpURLConnection conn = (HttpURLConnection) URL. openConnection (); conn. setRequestMethod (GET); conn. setConnectTimeout (5000); conn. setReadTimeout (5000); if (conn. getResponseCode () = 200) {// get the length of the requested resource file int length = conn. getContentLength (); // set the maximum value of the progress bar to the total length of the original file pb. setMax (length); File file = new File (Environment. ge TExternalStorageDirectory (), fileName); // generate a temporary file. rwd indicates that the file is directly written to the disk, instead of caching part of the file in the middle. This prevents power failure and some data has not been written to the disk; randomAccessFile raf = new RandomAccessFile (file, rwd); // set the size of the temporary file in advance. setLength (length); // remember to close raf. close (); // calculate the number of bytes that each thread should download, int size = length/ThreadCount; for (int I = 0; I <ThreadCount; I ++) {// start and end positions of the computing thread: int startIndex = I * size; int endIndex = (I + 1) * size-1; // if it is the last thread, then the end position is written to the dead if (I = ThreadCount-1) {endIndex = length-1;} // System. out. println (the download interval of thread + I + is: + startIndex + --- + endIndex); // new DownLoadThread () is in the for () loop, so there are three threads, that's right! New DownLoadThread (startIndex, endIndex, I ). start () ;}} catch (Exception e) {// TODO Auto-generated catch blocke. printStackTrace () ;}}; t. start ();} 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 ru N () {// send an http request again. Download the original file try {// generate a. txt file to save the ending index after the last downloaded file, then, set File progressFile = new File (Environment. getExternalStorageDirectory (), threadId +. txt); // determine whether the progress temporary file exists if (progressFile. exists () {FileInputStream FCM = new FileInputStream (progressFile); BufferedReader br = new BufferedReader (new InputStreamReader (FCM )); // read the total progress of the last download from the Progress temporary file and add it to the original start position to obtain the new start position int lastProgress = Integer. parseInt (br. rea DLine (); startIndex + = lastProgress; // display the progress of the last download to the progress bar currentProgress + = lastProgress; // refresh the progress bar, which can be displayed in the Child thread, analyze the cause in the future. // it should be handled internally by petabytes. setProgress (currentProgress); // sends a message so that the main thread refreshes the text progress handler. sendEmptyMessage (1); FCM. close ();} System. out. println (the download interval of thread + threadId + is: + startIndex + --- + endIndex); HttpURLConnection conn; URL url = new URL (path); conn = (HttpURLConnection) url. openConnection (); conn. se TRequestMethod (GET); conn. setConnectTimeout (5000); conn. setReadTimeout (5000); // set the range of the data requested by this http request conn. setRequestProperty (Range, bytes = + startIndex +-+ endIndex); // request some data with the corresponding code 206if (conn. getResponseCode () = 206) {// in the stream, only 1/3 of the data in the original file is InputStream is = conn. getInputStream (); byte [] B = new byte [1024]; int len = 0; int total = 0; // get the output stream File of the temporary file = new File (Environment. getExternalStorageDirectory (), fil EName); RandomAccessFile raf = new RandomAccessFile (file, rwd); // move the file write location to startIndex. // This is why we use RandomAccessFile instead of FileOutputStream, // because its seek method can easily locate raf in the file. seek (startIndex); while (len = is. read (B ))! =-1) {// after reading the data in the stream, write the data to the temporary file raf synchronously. write (B, 0, len); total + = len; System. out. println (thread + threadId + downloaded + total); // after each read of the data in the stream, the length of the data read this time is displayed to the progress bar currentProgress + = len; pb. setProgress (currentProgress); // sends a message so that the main thread refreshes the text progress handler. sendEmptyMessage (1); // generate a temporary file named RandomAccessFile progressRaf = new RandomAccessFile (progressFile, rwd), which is used to record the download progress. // after each data read from the stream, synchronously write the total download progress of the current thread to the Progress temporary file progressRaf. write (total + ). get Bytes (); progressRaf. close ();} System. out. println (thread + threadId + download completed ------------------- Xiaozhi parameter !); Raf. close (); finishedThread ++; synchronized (path) {if (finishedThread = ThreadCount) {for (int I = 0; I <ThreadCount; I ++) {File f = new File (Environment. getExternalStorageDirectory (), I +. txt); f. delete () ;}finishedthread = 0 ;}}} catch (Exception e) {// TODO Auto-generated catch blocke. printStackTrace ();}}}}

Activity_main.xml

 

 

 
  
   
    
   
 

Note:You can also use methods written by others on Github to directly call them;

 

 

Related Article

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.