Android Note 4-multi‑thread resumable upload, Android 4-resumable upload

Source: Internet
Author: User

Android Note 4-multi‑thread resumable upload, Android 4-resumable upload



Multi‑thread resumable data transfer is extremely important on any platform. Old Rules: Use a picture to introduce today's content.

If you cannot see the image clearly, right-click it and open it in a new window.



The principle is also very simple. multithreading means that a file is divided into different parts for direct download by multiple threads. resumable upload uses a text file to record the current download volume, at the beginning, you can read the text download value.


Check the Code directly.

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 (Bundl E savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); // The progress bar is used to display the current download progress. The total number of bytes of the download is used as the SS, and the total size of the target file is used 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 (); con N. setRequestMethod ("GET"); conn. setConnectTimeout (8000); conn. setReadTimeout (8000); if (conn. getResponseCode () = 200) {// get the total length of the object to be downloaded int length = conn. getContentLength (); // generate a temporary File in sequence. The size of the temporary file is the same as that of the target File. File file = new File (Environment. getExternalStorageDirectory (), getFileName (path); RandomAccessFile raf = new RandomAccessFile (file, "rwd"); raf. setLength (length); raf. close (); // set the progress bar to the total length of the target file pb. setMax (leng Th); // calculate the length of each thread to download int size = length/threadCount; // calculate the start position and end position of each thread for (int I = 0; I <threadCount; I ++) {int startIndex = I * size; int endIndex = (I + 1) * size-1; if (I = threadCount-1) endIndex = length-1; // System. out. the download interval of println ("Thread" + I + "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 () {// enable the sub-thread to download the target File. try {File fileProgess = new File (Environment. getExternalStorageDirectory (), threadId + ". txt "); int lastTotal = 0; // determines whether a temporary text file exists if (fileProgess. exists () {FileInputStream FCM = new FileInputStream (fileProgess); BufferedReader br = new BufferedReader (new InputStreamReader (); // Get the progress of the Previous download. lastTotal = Integer. parseInt (br. readLine (); // change the start position of the download. If you have already downloaded the data, do not request startIndex + = lastTotal again. close (); // write the progress of the Previous download to the progress bar currentPbProgress + = lastTotal; pb. setProgress (currentPbProgress); handler. sendEmptyMessage (0);} System. out. the final download interval of println ("Thread" + threadId + "is:" + startIndex + "~ "+ EndIndex); URL url = new URL (path); HttpURLConnection conn = (HttpURLConnection) url. openConnection (); conn. setRequestMethod ("GET"); conn. setConnectTimeout (8000); conn. setReadTimeout (8000); // defines the range of the requested data conn. setRequestProperty ("Range", "bytes =" + startIndex + "-" + endIndex); if (conn. getResponseCode () = 206) {// the data in the stream is only the data from startIndex to endIndex, and does not contain all data in 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 start position of data written to raf. seek (startIndex); while (len = is. read (B ))! =-1) {total + = len; System. out. println ("Thread" + threadId + "the number of downloaded bytes is:" + total); raf. write (B, 0, len); // in order to complete resumable upload, The while LOOP writes the RandomAccessFile rafProgress = new RandomAccessFile (fileProgess, "rwd"); rafProgress. write (total + ""). getBytes (); rafProgress. close (); currentPbProgress + = len; // every time all threads Download The len Length byte, It will be written to the progress bar of the total progress petabytes. setProgress (currentPbProgress); handler. sendEmptyMessage (0);} System. out. println ("Thread" + threadId + "download completed -------------------"); raf. close (); finishedThreadCount ++; // after all three threads have been downloaded, delete the temporary text file synchronized (path) {if (finishedThreadCount = 3) {for (int I = 0; I <threadCount; I ++) {File f = new File (Environment. getExternalStorageDirectory (), I + ". txt "); if (f. exists () f. delete () ;} finishedThreadCount = 0 ;}}} catch (Exception e) {// TODO Auto-generated catch blocke. printStackTrace ();}}}}


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.