|
Package cn. itcast. download;
Import java. io. File;
Import java. io. FileInputStream;
Import java. io. FileNotFoundException;
Import java. io. FileOutputStream;
Import java. io. IOException;
Import java. io. InputStream;
Import java. io. RandomAccessFile;
Import java.net. HttpURLConnection;
Import java.net. MalformedURLException;
Import java.net. ProtocolException;
Import java.net. URL;
Import cn. itcast. mutiledownload. StreamTool;
Import android. app. Activity;
Import android. OS. Bundle;
Import android. OS. Handler;
Import android. OS. Message;
Import android. view. View;
Import android. view. View. OnClickListener;
Import android. widget. Button;
Import android. widget. EditText;
Import android. widget. ProgressBar;
Import android. widget. TextView;
Import android. widget. Toast;
Public class MutiledownloadActivity extends Activity implements OnClickListener {
Private ProgressBar pb;
Private Button bt;
Private TextView TV;
Private EditText et;
Boolean flag = true;
Boolean stopflag = false;
Private Handler handler = new Handler (){
@ Override
Public void handleMessage (Message msg ){
Pb. setProgress (total );
Int max = pb. getMax ();
If (total> = (max-1 )){
Total = max;
Flag = false;
}
Int result = total * 100/max;
TV. setText ("current progress:" + result + "% ");
Super. handleMessage (msg );
}
};
Int total = 0;
@ Override
Public void onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );
SetContentView (R. layout. main );
Pb = (ProgressBar) this. findViewById (R. id. pb );
Bt = (Button) this. findViewById (R. id. bt );
TV = (TextView) this. findViewById (R. id. TV _process );
Et = (EditText) this. findViewById (R. id. et );
Bt. setOnClickListener (this );
}
@ Override
Public void onClick (View v ){
Switch (v. getId ()){
Case R. id. bt:
// Create a subthread to regularly update the ui
If ("start to download". equals (bt. getText (). toString ())){
Bt. setText ("paused ");
Stopflag = false; // start download
}
Else {
Bt. setText ("START download ");
Stopflag = true;
}
New Thread (){
@ Override
Public void run (){
Super. run ();
While (flag ){
Try {
Sleep (1000 );
// If total> = file length
Message msg = new Message ();
Handler. sendMessage (msg );
} Catch (InterruptedException e ){
E. printStackTrace ();
}
}
}
}. Start ();
// Start the download operation
String path = et. getText (). toString (). trim ();
If ("". equals (path )){
Toast. makeText (this, "path cannot be blank", 1). show ();
Return;
}
Try {
URL url = new URL (path );
HttpURLConnection conn = (HttpURLConnection) url
. OpenConnection ();
Conn. setRequestMethod ("GET ");
Conn. setConnectTimeout (5000 );
Conn. setRequestProperty ("User-Agent ",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1 )");
Int code = conn. getResponseCode ();
If (code = 200 ){
Int len = conn. getContentLength ();
RandomAccessFile file = new RandomAccessFile (
"/Mnt/sdcard/" + getFilenName (path), "rwd ");
// 1. Set the local file size to the same as the Server File Size
File. setLength (len );
// Set the maximum value of the progress bar
Pb. setMax (len );
// 2. Assume that three threads are enabled.
Int threadnumber = 3;
Int blocksize = len/threadnumber;
/**
* Thread 1 0 ~ Blocksize thread 2 1 * bolocksize ~ 2 * blocksize thread 3
* 2 * blocksize ~ End of File
*/
For (int I = 0; I <threadnumber; I ++ ){
Int startposition = I * blocksize;
Int endpositon = (I + 1) * blocksize;
If (I = (threadnumber-1 )){
// The last thread
Endpositon = len;
}
DownLoadTask task = new DownLoadTask (I, path,
Startposition, endpositon );
Task. start ();
}
}
} Catch (Exception e ){
Toast. makeText (this, "Download exception", 0). show ();
E. printStackTrace ();
}
Break;
}
}
Class DownLoadTask extends Thread {
Int threadid;
String filepath;
Int startposition;
Int endpositon;
Public DownLoadTask (int threadid, String filepath, int startposition,
Int endpositon ){
This. threadid = threadid;
This. filepath = filepath;
This. startposition = startposition;
This. endpositon = endpositon;
}
@ Override
Public void run (){
Try {
File postionfile = new File ("/mnt/sdcard/" + threadid + ". txt ");
URL url = new URL (filepath );
HttpURLConnection conn = (HttpURLConnection) url
. OpenConnection ();
System. out. println ("Thread" + threadid + "downloading" + "start position :"
+ Startposition + "end position" + endpositon );
If (postionfile. exists ()){
FileInputStream FCM = new FileInputStream (postionfile );
Byte [] result = StreamTool. getBytes (SOx );
String str = new String (result );
If (! "". Equals (str )){
Int newstartposition = Integer. parseInt (str );
If (newstartposition> startposition ){
Startposition = newstartposition;
}
}
}
// "Range", "bytes = 2097152-4194303 ")
Conn. setRequestProperty ("Range", "bytes =" + startposition + "-"
+ Endpositon );
Conn. setRequestMethod ("GET ");
Conn. setConnectTimeout (5000 );
Conn. setRequestProperty ("User-Agent ",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1 )");
InputStream is = conn. getInputStream ();
RandomAccessFile file = new RandomAccessFile ("/mnt/sdcard /"
+ GetFilenName (filepath), "rwd ");
// Set the position where the data is written from the file
File. seek (startposition );
Byte [] buffer = new byte [1024];
Int len = 0;
// Represents the location of the server data currently read, and the location of the file with this value already stored
Int currentPostion = startposition;
// Create a file object to record the download location of the current file
While (len = is. read (buffer ))! =-1 ){
If (stopflag ){
Return;
}
File. write (buffer, 0, len );
Synchronized (MutiledownloadActivity. this ){
Total + = len;
}
CurrentPostion + = len;
// The currentPostion information needs to be persistently stored on the storage device.
String position = currentPostion + "";
FileOutputStream fos = new FileOutputStream (postionfile );
Fos. write (position. getBytes ());
Fos. flush ();
Fos. close ();
}
File. close ();
System. out. println ("Thread" + threadid + "download completed ");
// Delete the object after the thread download is complete.
If (postionfile. exists ()){
Postionfile. delete ();
}
} Catch (Exception e ){
E. printStackTrace ();
}
Super. run ();
}
}
Public String getFilenName (String path ){
Int start = path. lastIndexOf ("/") + 1;
Return path. substring (start, path. length ());
}
}
|