歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android 多線程並發下載文件

Android 多線程並發下載文件

日期:2017/3/1 10:46:15   编辑:Linux編程

Download.java

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