Android 多线程并发下载文件


Download.java

  1. package com.wansha;  
  2.   
  3. import Android.app.Activity;  
  4. import android.os.Bundle;  
  5. import android.os.Handler;  
  6. import android.os.Message;  
  7. import android.util.Log;  
  8. import android.view.View;  
  9. import android.view.View.OnClickListener;  
  10. import android.widget.Button;  
  11. import android.widget.ProgressBar;  
  12.   
  13. import com.wansha.download.util.DownloadUtil;  
  14.   
  15. public class Download extends Activity {  
  16.     private ProgressBar bar1;  
  17.     private Button downFile;  
  18.     /** Called when the activity is first created. */  
  19.     @Override  
  20.     public void onCreate(Bundle savedInstanceState) {  
  21.         super.onCreate(savedInstanceState);  
  22.         setContentView(R.layout.main);  
  23.         this.bar1 = (ProgressBar)this.findViewById(R.id.bar1);  
  24.         this.downFile = (Button)this.findViewById(R.id.downfile);  
  25.         this.downFile.setOnClickListener(new downFileListener());  
  26.           
  27.     }  
  28.     class downFileListener implements OnClickListener{  
  29.         public void onClick(View arg0) {  
  30.             bar1.setVisibility(View.VISIBLE);  
  31.             DownloadUtil downloadutil = new DownloadUtil();  
  32.             downloadutil.Save2SDCard("http://192.168.0.137:8080/navigater/admin/SSHDemo.zip""peng/""sharp.zip");  
  33.               
  34.         }  
  35.     }  
  36.     Handler handler = new Handler(){  
  37.         public void handleMessage(Message msg) {  
  38.             Log.d("mydebug""hehh!" + msg.arg1);  
  39.             bar1.setProgress(msg.arg1);  
  40.             if(msg.arg1==100){  
  41.                 bar1.setVisibility(View.GONE);  
  42.             }  
  43.         };  
  44.     };  
  45. }  
DownloadFile.java
  1. package com.wansha.download.util;  
  2.   
  3. import java.io.BufferedInputStream;  
  4. import java.io.File;  
  5. import java.io.InputStream;  
  6. import java.net.HttpURLConnection;  
  7. import java.net.URL;  
  8.   
  9. import android.util.Log;  
  10.   
  11. public class DownloadFile {  
  12.     private File file;  
  13.     private String url;  
  14.     private String fileName;  
  15.     private int startPos;  
  16.     private int endPos;  
  17.     private long totalSize;  
  18.     private int threadNumTotal =1;  
  19.     private int currentThread =1;  
  20.     private static int BUFFER_SIZE = 1024*80;  
  21.       
  22.     public int getBUFFER_SIZE() {  
  23.         return BUFFER_SIZE;  
  24.     }  
  25.     public int getThreadNumTotal() {  
  26.         return threadNumTotal;  
  27.     }  
  28.     public void setThreadNumTotal(int threadNumTotal) {  
  29.         this.threadNumTotal = threadNumTotal;  
  30.     }  
  31.     public int getCurrentThread() {  
  32.         return currentThread;  
  33.     }  
  34.     public void setCurrentThread(int currentThread) {  
  35.         this.currentThread = currentThread;  
  36.     }  
  37.     public File getFile() {  
  38.         return file;  
  39.     }  
  40.     public void setFile(File file) {  
  41.         this.file = file;  
  42.     }  
  43.     public String getUrl() {  
  44.         return url;  
  45.     }  
  46.     public void setUrl(String url) {  
  47.         this.url = url;  
  48.     }  
  49.     public String getFileName() {  
  50.         return fileName;  
  51.     }  
  52.     public void setFileName(String fileName) {  
  53.         this.fileName = fileName;  
  54.     }  
  55.     public int getStartPos() {  
  56.         return startPos;  
  57.     }  
  58.     public void setStartPos(int startPos) {  
  59.         this.startPos = startPos;  
  60.     }  
  61.     public int getEndPos() {  
  62.         return endPos;  
  63.     }  
  64.     public void setEndPos(int endPos) {  
  65.         this.endPos = endPos;  
  66.     }  
  67.     public long getTotalSize() {  
  68.         return totalSize;  
  69.     }  
  70.     public void setTotalSize(long totalSize) {  
  71.         this.totalSize = totalSize;  
  72.     }  
  73.       
  74.     public long getURLTotalSize() {  
  75.         try{  
  76.             URL url = new URL(this.url);  
  77.             HttpURLConnection httpConn = (HttpURLConnection)url.openConnection();  
  78.             httpConn.setRequestMethod("GET");                         //以GET方式连接     
  79.             if(httpConn.getResponseCode() == HttpURLConnection.HTTP_OK){  
  80.                 return httpConn.getContentLength();  
  81.             }  
  82.         }catch(Exception ex){  
  83.             ex.printStackTrace();  
  84.             return 0;  
  85.         }  
  86.         return 0;  
  87.     }  
  88.       
  89.     public InputStream getInputStreamByThreadNum(){  
  90.         InputStream is = null;  
  91.         try{  
  92.             if(this.url != null && !"".equals(this.url)){  
  93.                 long urlTotalSize = getURLTotalSize();  
  94.                 Log.d("mydebug""threadNumTotal         " + this.threadNumTotal);  
  95.                 long spanSize = (long)Math.ceil((float)urlTotalSize/this.threadNumTotal);  
  96.                 Log.d("mydebug""spanSize         " + spanSize);  
  97.                 this.setStartPos((int)((this.currentThread-1)*spanSize));  
  98.                 int ends = (int)(this.currentThread*spanSize-1);  
  99.                 if(ends > urlTotalSize){  
  100.                     this.setEndPos((int)urlTotalSize-1);  
  101.                 }else{  
  102.                     this.setEndPos(ends);  
  103.                 }  
  104.                   
  105.                 URL url = new URL(this.url);  
  106.                 HttpURLConnection httpConn = (HttpURLConnection)url.openConnection();  
  107.                 httpConn.setRequestMethod("GET");                         //以GET方式连接     
  108.                 httpConn.setRequestProperty("Connection""Keep-Alive");  //保持一直连接     
  109.                 httpConn.setConnectTimeout(60 * 1000 * 5);                //连接超时5分钟     
  110.                 httpConn.setAllowUserInteraction(true);    
  111.                 httpConn.setRequestProperty("Range""bytes=" + getStartPos() + "-" + getEndPos());  
  112.                 Log.d("mydebug""         " + getStartPos() + "            " + getEndPos());  
  113.                 is = new BufferedInputStream(httpConn.getInputStream(),DownloadFile.BUFFER_SIZE);  
  114.             }  
  115.         }catch(Exception ex){  
  116.             ex.printStackTrace();  
  117.         }  
  118.         return is;  
  119.     }  
  120.       
  121.     public InputStream getInputStreamByPos(){  
  122.         try{  
  123.             if(this.url != null && !"".equals(this.url)){  
  124.                 if(this.startPos != 0 || this.endPos != 0){  
  125.                     URL url = new URL(this.url);  
  126.                     HttpURLConnection httpConn = (HttpURLConnection)url.openConnection();  
  127.                     httpConn.setRequestMethod("GET");                         //以GET方式连接     
  128.                     httpConn.setRequestProperty("Connection""Keep-Alive");  //保持一直连接     
  129.                     httpConn.setConnectTimeout(60 * 1000 * 5);                //连接超时5分钟     
  130.                     httpConn.setAllowUserInteraction(true);    
  131.                     httpConn.setRequestProperty("Range""bytes=" + getStartPos() + "-" + getEndPos());    
  132.                     Log.d("mydebug""readding....6           " + httpConn.getResponseCode());  
  133. //                  if(httpConn.getResponseCode() == HttpURLConnection.HTTP_OK){   
  134.                         Log.d("mydebug""readding....8           " + this.startPos + "````````````````````````" + this.endPos);  
  135.                             Log.d("mydebug""hello world");  
  136. //                          httpConn.setRequestProperty("Range", "bytes=" + getStartPos() + "-" + getEndPos());     
  137.                             Log.d("mydebug""start ------>" + this.startPos + "  endPos" + this.endPos);  
  138.                             Log.d("mydebug""readding....7");  
  139.                             return new BufferedInputStream(httpConn.getInputStream(),DownloadFile.BUFFER_SIZE);  
  140.       
  141. //                  }   
  142.                 }  
  143.             }  
  144.         }catch(Exception ex){  
  145.             ex.printStackTrace();  
  146.             return null;  
  147.         }  
  148.         return null;  
  149.     }  
  150.     public static void main(String[] args) throws Exception {  
  151.         DownloadFile downloadFile = new DownloadFile();  
  152.         downloadFile.setUrl("http://www.baidu.com/index.html");  
  153.         downloadFile.getInputStreamByPos();  
  154.     }  
  155. }  
DownloadUtil.java
  1. package com.wansha.download.util;  
  2.   
  3. import java.io.File;  
  4. import java.io.InputStream;  
  5. import java.io.RandomAccessFile;  
  6. import java.util.concurrent.CountDownLatch;  
  7. import java.util.concurrent.ExecutorService;  
  8. import java.util.concurrent.Executors;  
  9.   
  10. import android.os.Environment;  
  11. import android.os.Handler;  
  12. import android.os.Message;  
  13. import android.util.Log;  
  14.   
  15. public class DownloadUtil {  
  16.     private static int threadNum = 10;  
  17.     private int sign = 0;  
  18.     public static int getThreadNum() {  
  19.         return threadNum;  
  20.     }  
  21.   
  22.     public static void setThreadNum(int threadNum) {  
  23.         DownloadUtil.threadNum = threadNum;  
  24.     }  
  25.   
  26.     public DownloadUtil(){  
  27.           
  28.     }  
  29.   
  30.     private final static String SDPATH = Environment.getExternalStorageDirectory().getPath() + "/";  
  31.       
  32.     public boolean isExistFile(String filePath){  
  33.         File file = new File(filePath);  
  34.         return file.exists();  
  35.     }  
  36.       
  37.     public void createDir(String dirPath){  
  38.         if(dirPath != null || !"".equals(dirPath)){  
  39.             File file = new File(dirPath);  
  40.             if(!file.isDirectory()){  
  41.                 file.mkdirs();  
  42.             }  
  43.         }  
  44.     }  
  45.       
  46.     public int Save2SDCard(String urlAddress, String saveDir, String fileName){  
  47.         createDir(DownloadUtil.SDPATH + saveDir);  
  48.         try{  
  49.         File file = new File(DownloadUtil.SDPATH + saveDir, fileName);  
  50.         Log.d("mydebug""fileName....1" + DownloadUtil.SDPATH + saveDir + fileName);  
  51.         if(file.exists())file.delete();  
  52.         ExecutorService service = Executors.newFixedThreadPool(10);  
  53.         CountDownLatch countDownLatch = new CountDownLatch(DownloadUtil.threadNum);  
  54.         Log.d("mydebug""readding....1");  
  55.         for(int i=1; i<=DownloadUtil.threadNum; i++){  
  56.             Log.d("mydebug""readding....2");  
  57.             DownloadFile downloadFile = new DownloadFile();  
  58.                 downloadFile.setUrl(urlAddress);  
  59.                 downloadFile.setThreadNumTotal(DownloadUtil.threadNum);  
  60.                 downloadFile.setCurrentThread(i);  
  61.             RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rwd");  
  62.               
  63.               
  64. //          boolean flag = this.handler.post(new SaveFileThread(countDownLatch, this.handler));   
  65.             service.execute(new SaveFileThread(randomAccessFile, downloadFile, countDownLatch));  
  66.         }  
  67.         countDownLatch.await();  
  68.         service.shutdown();  
  69.         Log.d("mydebug""download is finish!");  
  70.         return 0;  
  71.         }catch(Exception ex){  
  72.             ex.printStackTrace();  
  73.             return -1;  
  74.         }  
  75.     }  
  76.       
  77.     class MyRunnable implements Runnable{  
  78.         private Handler handler;  
  79.         public MyRunnable(){  
  80.                
  81.         }  
  82.         public MyRunnable(Handler handler){  
  83.             this.handler = handler;  
  84.         }  
  85.         public void run() {  
  86.                 sign += 10;  
  87.                 Message message = this.handler.obtainMessage();  
  88.                 message.arg1 = sign;  
  89.                 try{  
  90.                     Thread.sleep(2000);  
  91.                 }catch(Exception ex){  
  92.                     ex.printStackTrace();  
  93.                 }  
  94.                 this.handler.sendMessage(message);  
  95.         };  
  96.   
  97.     };  
  98.       
  99.     class SaveFileThread implements Runnable{  
  100.         private RandomAccessFile randomFile;  
  101.         private DownloadFile downloadFile;  
  102.         private CountDownLatch countDownLatch;  
  103.         public SaveFileThread() {  
  104.         }  
  105.   
  106.         public SaveFileThread(RandomAccessFile randomFile, DownloadFile downloadFile, CountDownLatch countDownLatch) {  
  107.             this.randomFile = randomFile;  
  108.             this.downloadFile = downloadFile;  
  109.             this.countDownLatch = countDownLatch;  
  110.         }  
  111.   
  112.   
  113.         public void run() {  
  114.             try{  
  115.                 InputStream is = this.downloadFile.getInputStreamByThreadNum();  
  116.                 this.randomFile.seek(this.downloadFile.getStartPos());  
  117.                   
  118.                 byte[] by = new byte[1024*80];  
  119.                 int length = 0;  
  120.                   
  121.                 while(-1 != (length = is.read(by))){  
  122.                     this.randomFile.write(by, 0, length);  
  123.                 }  
  124.                   
  125.                 is.close();  
  126.                 this.randomFile.close();  
  127.                 this.countDownLatch.countDown();  
  128.                   
  129.             }catch(Exception ex){  
  130.                 ex.printStackTrace();  
  131.             }  
  132.         }  
  133.     }  
  134. }  

相关内容