Android single-thread download and multi-thread download

Source: Internet
Author: User
Tags integer division

Android single-thread download and multi-thread download
Overview:

Single-threaded download is simple, that is, enabling a thread to download resources and then saving them locally;

Multi-thread download uses RandomAccessFile (random file read/write operation class) to set the start point position for each thread to read files. The length between the start points is the size of the files to be downloaded by this thread.

Download start position: thread id * length of data downloaded by each thread =?

Download end position: (thread id + 1) * length of data downloaded by each thread-1 =?
URLConnection is used here.

Single-thread download and multi-thread download
Public class DownloadActivity extends Activity implements View. onClickListener {private Button mButtonSingle; private Button mButtonMuti; private SeekBar mSeekBarDownload; private int fileLength; // handler is used to receive messages from multithreading download threads, and get the file download progress write progress bar SeekBar private Handler handler = new Handler () {@ Override public void handleMessage (Message msg) {switch (msg. what) {case 0x23: mSeekBarDownload. setProgress (Msg. arg1 * 100/fileLength); break ;}};@ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_download); mSeekBarDownload = (SeekBar) findViewById (R. id. seekBar_download); mButtonSingle = (Button) findViewById (R. id. button_download_single); mButtonMuti = (Button) findViewById (R. id. button_download_muti); mButtonSingle. setOn ClickListener (this); mButtonMuti. setOnClickListener (this) ;}@ Override public void onClick (View v) {switch (v. getId () {case R. id. button_download_single: new singledownloadtask(cmd.exe cute (); break; case R. id. button_download_muti: new Thread (new Runnable () {@ Override public void run () {downloadMuti ();}}). start (); break; default: break;}/*** multi‑thread Download Method * is used to open a network connection and create a storage path for the downloaded file, enable multiple download threads and send the file download progress Message of */private void downloadMuti () {try {String urlPath = http: // 192.168.0.30: 8080/MyWebTest/music/aa133; URL url = new URL (urlPath ); // connect URLConnection connection = url. openConnection (); // get the file length fileLength = connection. getContentLength (); // locate or create the storage path of the downloaded File. file File = new file(environment.getexternalstoragedirectory(folder, ee1_); if (! File. exists () {file. createNewFile ();} MutiThread [] threads = new MutiThread [5]; // perform five multipart downloads because the integer division will discard the remainder, the download length of the last process ranges from 4/5 of the file length to the total file length for (int I = 0; I <5; I ++) {MutiThread thread = null; if (I = 4) {thread = new MutiThread (fileLength/5*4, fileLength, urlPath, file. getAbsolutePath ();} else {thread = new MutiThread (fileLength/5 * I, fileLength/5 * (I + 1)-1, urlPath, file. getAbsolutePath ();} thread. start (); threads [I] = thread;} boolean isFinish = true; // If the download progress is continuously updated when the download is not complete, the data is transmitted to handler while (isFinish) through Message) {int sum = 0; for (MutiThread thread: threads) {sum + = thread. getSum ();} Message msg = handler. obtainMessage (); msg. what = 0x23; msg. arg1 = sum; handler. sendMessage (msg); // generally, a downloaded file may not be able to be downloaded completely if (sum + 10> fileLength) {isFinish = false;} // The second after the download, update a progress Thread. sleep (1000) ;}} catch (MalformedURLException e) {e. printStackTrace ();} catch (IOException e) {e. printStackTrace ();} catch (InterruptedException e) {e. printStackTrace () ;}}// single-thread download, which uses AsyncTask Thread class SingleDownloadTask extends AsyncTask
  
   
{@ Override protected void onProgressUpdate (Integer... values) {super. onProgressUpdate (values); mSeekBarDownload. setProgress (int) (values [0] * 100.0/values [1]);} @ Override protected void onPostExecute (String s) {super. onPostExecute (s) ;}@ Override protected String doInBackground (String... params) {try {URL url = new URL (http: // 192.168.0.30: 8080/MyWebTest/music/aa.mp3); URLConnection connection = Url. openConnection (); int length = connection. getContentLength (); InputStream is = connection. getInputStream (); File file = new file(environment.getexternalstoragedirectory(),aa1_); if (! File. exists () {file. createNewFile ();} FileOutputStream fos = new FileOutputStream (file); byte [] array = new byte [1024]; int index = is. read (array); int progress = 0; while (index! =-1) {fos. write (array, 0, index); progress + = index; publishProgress (progress, length); index = is. read (array);} fos. flush (); fos. close (); is. close ();} catch (MalformedURLException e) {e. printStackTrace ();} catch (IOException e) {e. printStackTrace () ;}return null ;}}}
  

Multi-thread download thread writing

Public class MutiThread extends Thread {private int sum = 0; private long start; private long end; private String urlPath; private String filePath; public MutiThread (long start, long end, String urlPath, string filePath) {this. start = start; this. end = end; this. urlPath = urlPath; this. filePath = filePath;} public int getSum () {return sum;} @ Override public void run () {try {URL url = new URL (UrlPath); URLConnection connection = url. openConnection (); connection. setAllowUserInteraction (true); // you can specify the start point and end point of the download from the current thread. setRequestProperty (Range, bytes = + start +-+ end); InputStream is = connection. getInputStream (); byte [] array = new byte [1024]; File file = new File (filePath ); // use RandomAccessFile in java to perform random read/write operations on the file RandomAccessFile randomAccessFile = new RandomAccessFile (file, rw );// Set the start File Location randomAccessFile. seek (start); int index = is. read (array); // The start loop reads and writes the file in the form of a stream while (index! =-1) {randomAccessFile. write (array, 0, index); sum + = index; index = is. read (array);} randomAccessFile. close (); is. close ();} catch (MalformedURLException e) {e. printStackTrace ();} catch (IOException e) {e. printStackTrace ();}}}

Result demonstration:
Single-thread download:

Multi-thread download:

Obviously, multi-thread download is much faster than single-thread download, provided that the mobile phone is multi-core.

 

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.