Android multi-thread download

Source: Internet
Author: User

 

Package my. Thread;

 

Import java. io. BufferedInputStream;

Import java. io. RandomAccessFile;

Import java.net. HttpURLConnection;

Import java.net. URL;

Import java.net. URLConnection;

Import java. util. concurrent. CountDownLatch;

 

 

Import android. app. Activity;

Import android. OS. Bundle;

Import android. OS. Environment;

Import android. view. View;

Import android. view. View. OnClickListener;

Import android. widget. Button;

Import android. widget. TextView;

 

Public class ManyThreadActivity extends Activity {

/** Called when the activity is first created .*/

Private Button button;

Private TextView textView;

Private static final int THREAD_COUNT = 4;

Private CountDownLatch latch = new CountDownLatch (THREAD_COUNT );

Private long completeLength = 0;

Private long fileLength;

Public static String SaveFile = Environment. getExternalStorageDirectory () + "/DownFile/" + "test. Mp3 ";

Public static final String url = "http: // 210.30.12.33: 8080/mp3/Beyond.mp3 ";

@ Override

Public void onCreate (Bundle savedInstanceState ){

Super. onCreate (savedInstanceState );

SetContentView (R. layout. main );

Button = (Button) findViewById (R. id. button1 );

TextView = (TextView) findViewById (R. id. editText1 );

TextView. setText (url );

Button. setOnClickListener (new MyListener ());

}

Class MyListener implements OnClickListener {

 

@ Override

Public void onClick (View v ){

// TODO Auto-generated method stub

Try {

Download (url );

} Catch (Exception e ){

// TODO Auto-generated catch block

E. printStackTrace ();

}

}

}

 

// Download thread

Class DownloadThread extends Thread {

Private URL;

Private RandomAccessFile file;

Private long from;

Private long end;

 

/**

* @ Param url: the download URL.

* @ Param file the file stored after the download is complete

* @ Param from start position of the file corresponding to the current thread

* @ Param end the end position of the file corresponding to the current thread

*/

DownloadThread (URL url, RandomAccessFile file, long from, long end ){

This. url = url;

This. file = file;

This. from = from;

This. end = end;

}

 

Public void run (){

Try {

Long pos = from;

Byte [] buf = new byte [1024*8];

 

HttpURLConnection cn = (HttpURLConnection) url. openConnection ();

// Set the start position and end position of the request.

Cn. setRequestProperty ("Range", "bytes =" + from + "-" + end );

 

BufferedInputStream bis = new BufferedInputStream (cn. getInputStream ());

Int len;

While (len = bis. read (buf)> 0 ){

Synchronized (file ){

File. seek (pos );

File. write (buf, 0, len );

}

Pos + = len;

CompleteLength + = len;

System. out. println (completeLength * 100/fileLength + "% ");

}

Cn. disconnect ();

} Catch (Exception e ){

E. printStackTrace ();

}

Latch. countDown ();

}

}

 

Public void download (String address) throws Exception {

URL url = new URL (address );

URLConnection cn = url. openConnection ();

FileLength = cn. getContentLength ();

Long packageLength = fileLength/THREAD_COUNT; // The number of bytes to be downloaded by each thread

Long leftLength = fileLength % THREAD_COUNT; // remaining bytes

RandomAccessFile file = new RandomAccessFile (SaveFile, "rw ");

System. out. println (fileLength );

// Calculate the start position and end position of each thread request.

/*

* The starting position of the first thread is 0 ~ 0 + packageLength (number of bytes to be downloaded by each thread)

* The starting position of the second thread is endPos + 1 (packageLength + 1 of the first thread )~ EndPos + 1 + packageLength

* The starting position of the second thread is .........

*/

Long pos = 0;

For (int I = 0; I <THREAD_COUNT; I ++ ){

Long endPos = pos + packageLength;

New DownloadThread (url, file, pos, endPos). start ();

If (leftLength> 0 ){

EndPos ++;

LeftLength --;

}

Pos = endPos;

}

Latch. await ();

}

 

}

 

Save as testbench File

 

From Viagra ~ YZ

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.