Android learning history (6)-porting multi-thread downloads from java to Android (I .e., using multi-thread downloads in Android) ③

Source: Internet
Author: User
Tags file url

In this section, we will discuss how to use multi‑thread download and resumable upload in android. The first two sections are prepared for this section, but we have not read the first two sections, it is best to read the previous two articles before reading this article. In fact, android applications and java are basically similar, but on android, I suggest storing resumable upload records in the sqlite3 database of android. This is the best, of course, it is also stored in the SD card. For convenience, I did not create a database, but saved it directly to the SD card. Let's take a look at what I run in android as follows:

I added the progress bar display and the download progress percentage display in the code here. To keep the progress bar and percentage unchanged, I added a lock to the code used to calculate the download progress in the download process. As follows:

In addition, the following code saves the file recording the download progress to the SD card. We recommend that you use a database. The Code is as follows:

I have nothing to explain about other things. It is similar to the content in the previous article, and I have already written a lot of details in the Code. Let's take a look at the code!

The code in MainActivity is as follows:

 

Package net. loonggg. android. downloader; import java. io. file; import java. io. fileInputStream; import java. io. inputStream; import java. io. randomAccessFile; import java.net. httpURLConnection; import java.net. URL; import android. annotation. suppressLint; import android. app. activity; import android. OS. bundle; import android. OS. handler; import android. OS. message; import android. view. view; import android. view. window; im Port android. widget. button; import android. widget. editText; import android. widget. progressBar; import android. widget. textView; import android. widget. toast; @ SuppressLint (HandlerLeak) public class MainActivity extends Activity {public int currentProcess = 0; // current progress of File Download // Number of enabled threads public static final int THREAD_COUNT = 3; public static int runningThread = 3; // record the number of threads for running download files private EditText et; private Ton btn; private TextView TV; private ProgressBar pb; // download progress bar private Handler handler = new Handler () {public void handleMessage (android. OS. message msg) {switch (msg. arg1) {case 0: Toast. makeText (getApplicationContext (), download failed !, Toast. LENGTH_SHORT). show (); break; case 1: Toast. makeText (getApplicationContext (), download complete !, Toast. LENGTH_SHORT ). show (); break; case 2: TV. setText (download progress: + pb. getProgress () * 100/pb. getMax () + %); break; default: break ;}};@overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); requestWindowFeature (Window. FEATURE_NO_TITLE); setContentView (R. layout. activity_main); et = (EditText) findViewById (R. id. et); pb = (ProgressBar) findViewById (R. id. pb); btn = (Button) FindViewById (R. id. btn); TV = (TextView) findViewById (R. id. TV _process); btn. setOnClickListener (new View. onClickListener () {@ Overridepublic void onClick (View v) {downLoad () ;}}) ;}/ *** Method for downloading objects */private void downLoad () {final String path = et. getText (). toString (); new Thread () {public void run () {try {// 1. Connect to the server, obtain a file, and obtain the file length, create a local Temporary File URL with the same size as the Server File url = new URL (path); HttpURLConnection conn = (Htt PURLConnection) url. openConnection (); conn. setConnectTimeout (5000); conn. setRequestMethod (GET); int code = conn. getResponseCode (); if (code = 200) {// The length of the data returned by the server, which is actually the object length int length = conn. getContentLength (); pb. setMax (length); // set the maximum value for the progress bar System. out. println (---- total file length ---- + length); // create a temporary file named RandomAccessFile raf = new RandomAccessFile (/sdcard/temp.apk, rwd); // specify the length of the created file. se TLength (length); // disable rafraf. close (); // assume three threads are used to download resources. // The average file size of each thread is int blockSize = length/THREAD_COUNT; for (int threadId = 1; threadId <= THREAD_COUNT; threadId ++) {// the position where the first thread starts to download int startIndex = (threadId-1) * blockSize; int endIndex = threadId * blockSize-1; if (threadId = THREAD_COUNT) {endIndex = length;} System. out. println (---- threadId --- + -- startIndex -- + startIndex + -- endIndex -- + en DIndex); new DownloadThread (path, threadId, startIndex, endIndex ). start () ;}} catch (Exception e) {e. printStackTrace (); Message msg = new Message (); msg. arg1 = 0; handler. sendMessage (msg );}};}. start ();}/*** download the sub-Thread of the file. Each Thread downloads the file ** @ author loonggg **/public class DownloadThread extends Thread {private int threadId; private int startIndex; private int endIndex; private String path;/*** @ param path * Path of the downloaded file on the server * @ param threadId * thread id * @ param startIndex * start position of thread download * @ param endIndex * end position of thread download */public DownloadThread (String path, int threadId, int startIndex, int endIndex) {this. path = path; this. threadId = threadId; this. startIndex = startIndex; this. endIndex = endIndex ;}@ Overridepublic void run () {try {// check whether there is a file with a download length record. If there is data reading this file, replace it with the database ----------------------- ----- File tempFile = new File (/sdcard/+ threadId +. txt); if (tempFile. exists () & tempFile. length ()> 0) {FileInputStream FCM = new FileInputStream (tempFile); byte [] temp = new byte [1024*10]; int leng = Fi. read (temp); // The downloaded length String downloadLen = new String (temp, 0, leng); int downloadInt = Integer. parseInt (downloadLen); // ------------------ these two lines of code are the key code for setting the start point of the progress bar during resumable upload --------------- int alre AdyDownloadInt = downloadInt-startIndex; currentProcess + = alreadyDownloadInt; // calculate the length of the file downloaded at the last breakpoint of each thread. // The length of each file is startIndex = downloadInt. close () ;}// --------------------------------------------------------------- URL url = new URL (path); HttpURLConnection conn = (HttpURLConnection) url. openConnection (); conn. setRequestMetho D (GET); // important: Request the server to download part of the file and specify the position of the file conn. setRequestProperty (Range, bytes = + startIndex +-+ endIndex); conn. setConnectTimeout (5000); // status code of the slave server requesting all resources 200 OK if the status code of some resources requested by the slave server is 206 okint code = conn. getResponseCode (); System. out. println (--- code --- + code); InputStream is = conn. getInputStream (); // The request location has been set. The returned result is the input stream RandomAccessFile raf = new RandomAccessFile (/sdcard/temp.apk, rwd) of the file corresponding to the current location ); // start from where the file is written randomly Write raf. seek (startIndex); // locate the file int len = 0; byte [] buffer = new byte [1024]; int total = 0; // record the length of the downloaded data while (len = is. read (buffer ))! =-1) {RandomAccessFile recordFile = new RandomAccessFile (/sdcard/+ threadId +. txt, rwd); // record the download progress of each thread and Mark raf for resumable upload. write (buffer, 0, len); total + = len; recordFile. write (String. valueOf (startIndex + total ). getBytes (); recordFile. close (); // lock synchronization to prevent confusion synchronized (MainActivity. this) {currentProcess + = len; // obtain the current total progress. // In special cases, the progress bar and dialog box of ProgressBarH and ProgressDialog can be used to update the UI in the Child thread. The internal code of the system processes pb in special cases. setProgress (curren TProcess); // modify the progress of the progress bar on the interface Message msg = Message. obtain (); msg. arg1 = 2; // The percentage of handler in the update progress when an update message is sent. sendMessage (msg) ;}} is. close (); raf. close (); System. out. println (thread: + threadId + download completed !);} Catch (Exception e) {e. printStackTrace (); Message msg = handler. obtainMessage (); msg. arg1 = 0; handler. sendMessage (msg) ;}finally {threadFinish () ;}/ *** I personally think it is okay not to lock, but the lock may be safer. If anyone has good suggestions, please leave a message */private synchronized void threadFinish () {runningThread --; if (runningThread = 0) {// All threads have been executed for (int I = 1; I <= THREAD_COUNT; I ++) {// delete the File file File that records the download progress = new File (/sdcard/+ I +. txt); file. delete (); Message msg = handler. obtainMessage (); msg. arg1 = 1; handler. sendMessage (msg );}}}}}
The corresponding Activity_main.xml code is as follows:

 

 

     
      
       
    
     
    
   
  
 
Of course, do not forget to set network permissions and read/write SD card permissions in the list file:

 

 

 

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.