Android多線程斷點續傳下載


學習了多線程下載,而且可以斷點續傳的邏輯,線程數量可以自己選擇,但是線程數量過多手機就承受不起,導致閃退,好在有斷點續傳。

步驟寫在了代碼的注釋里。大概就是獲取服務器文件的大小,在本地新建一個相同大小的文件用來申請空間,然后將服務器的文件讀下來寫到申請的文件中去。若開多線程,將文件分塊,計算每個線程下載的開始位置和結束位置。若斷點傳輸,則保存斷開后下載的位置,下次將此位置賦給開始下載的位置即可。細節見代碼。

下面是效果圖:

 

 

 

布局文件activity_main.xml:

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
 3     xmlns:tools="http://schemas.android.com/tools"
 4     android:layout_width="match_parent"
 5     android:layout_height="match_parent"
 6     tools:context=".MainActivity">
 7 
 8     <LinearLayout
 9         android:layout_width="match_parent"
10         android:layout_height="match_parent"
11         android:orientation="vertical">
12 
13         <EditText
14             android:id="@+id/et_path"
15             android:layout_width="match_parent"
16             android:layout_height="wrap_content"
17             android:hint="請輸入下載路徑"
18             android:text="http://10.173.29.234/test.exe" />
19 
20         <EditText
21             android:id="@+id/et_threadCount"
22             android:layout_width="match_parent"
23             android:layout_height="wrap_content"
24             android:hint="請輸入線程數量" />
25 
26         <Button
27             android:layout_width="wrap_content"
28             android:layout_height="wrap_content"
29             android:onClick="click"
30             android:text="下載" />
31 
32         <LinearLayout
33             android:id="@+id/ll_pb"
34             android:layout_width="match_parent"
35             android:layout_height="match_parent"
36             android:background="#455eee"
37             android:orientation="vertical">
38 
39         </LinearLayout>
40     </LinearLayout>
41 
42 </android.support.constraint.ConstraintLayout>

創建布局文件,用來動態顯示每個線程的進度條

layout.xml:

1 <?xml version="1.0" encoding="utf-8"?>
2 <ProgressBar xmlns:android="http://schemas.android.com/apk/res/android"
3     android:id="@+id/progressBar"
4     style="?android:attr/progressBarStyleHorizontal"
5     android:layout_width="match_parent"
6     android:layout_height="wrap_content" />

MainActivity.java:

  1 import...;
  2 
  3 public class MainActivity extends AppCompatActivity {
  4 
  5     private EditText et_path;
  6     private EditText et_threadCount;
  7     private LinearLayout ll_pb;
  8     private String path;
  9 
 10     private static int runningThread;// 代表正在運行的線程
 11     private int threadCount;
 12     private List<ProgressBar> pbList;//集合存儲進度條的引用
 13 
 14     @Override
 15     protected void onCreate(Bundle savedInstanceState) {
 16         super.onCreate(savedInstanceState);
 17         setContentView(R.layout.activity_main);
 18 
 19         et_path = findViewById(R.id.et_path);
 20         et_threadCount = findViewById(R.id.et_threadCount);
 21         ll_pb = findViewById(R.id.ll_pb);
 22         //添加一個進度條的引用
 23         pbList = new ArrayList<ProgressBar>();
 24     }
 25 
 26     //點擊按鈕實現下載邏輯
 27     public void click(View view) {
 28         //獲取下載路徑
 29         path = et_path.getText().toString().trim();
 30         //獲取線程數量
 31         String threadCounts = et_threadCount.getText().toString().trim();
 32         //移除以前的進度條添加新的進度條
 33         ll_pb.removeAllViews();
 34         threadCount = Integer.parseInt(threadCounts);
 35         pbList.clear();
 36         for (int i = 0; i < threadCount; i++) {
 37             ProgressBar v = (ProgressBar) View.inflate(getApplicationContext(), R.layout.layout, null);
 38 
 39             //把v添加到幾何中
 40             pbList.add(v);
 41 
 42             //動態獲取進度條
 43             ll_pb.addView(v);
 44         }
 45 
 46         //java邏輯移植
 47         new Thread() {
 48             @Override
 49             public void run() {
 50                 /*************/
 51                 System.out.println("你好");
 52                 try {
 53                     URL url = new URL(path);
 54                     HttpURLConnection conn = (HttpURLConnection) url.openConnection();
 55                     conn.setRequestMethod("GET");
 56                     conn.setConnectTimeout(5000);
 57                     int code = conn.getResponseCode();
 58                     if (code == 200) {
 59                         int length = conn.getContentLength();
 60                         // 把運行線程的數量賦值給runningThread
 61                         runningThread = threadCount;
 62 
 63                         System.out.println("length=" + length);
 64                         // 創建一個和服務器的文件一樣大小的文件,提前申請空間
 65                         RandomAccessFile randomAccessFile = new RandomAccessFile(getFileName(path), "rw");
 66                         randomAccessFile.setLength(length);
 67                         // 算出每個線程下載的大小
 68                         int blockSize = length / threadCount;
 69                         // 計算每個線程下載的開始位置和結束位置
 70                         for (int i = 0; i < length; i++) {
 71                             int startIndex = i * blockSize;// 開始位置
 72                             int endIndex = (i + 1) * blockSize;// 結束位置
 73                             // 特殊情況就是最后一個線程
 74                             if (i == threadCount - 1) {
 75                                 // 說明是最后一個線程
 76                                 endIndex = length - 1;
 77                             }
 78                             // 開啟線程去服務器下載
 79                             DownLoadThread downLoadThread = new DownLoadThread(startIndex, endIndex, i);
 80                             downLoadThread.start();
 81 
 82                         }
 83 
 84                     }
 85                 } catch (MalformedURLException e) {
 86                     // TODO Auto-generated catch block
 87                     e.printStackTrace();
 88                 } catch (IOException e) {
 89                     // TODO Auto-generated catch block
 90                     e.printStackTrace();
 91                 }
 92                 /*************/
 93             }
 94         }.start();
 95 
 96     }
 97 
 98     private class DownLoadThread extends Thread {
 99         // 通過構造方法吧每個線程的開始位置和結束位置傳進來
100         private int startIndex;
101         private int endIndex;
102         private int threadID;
103         private int PbMaxSize;//代表當前下載(進度條)的最大值
104         private int pblastPosition;//如果中斷過,這是進度條上次的位置
105 
106         public DownLoadThread(int startIndex, int endIndex, int threadID) {
107             this.startIndex = startIndex;
108             this.endIndex = endIndex;
109             this.threadID = threadID;
110 
111         }
112 
113         @Override
114         public void run() {
115             // 實現去服務器下載文件
116             try {
117                 //計算進度條最大值
118                 PbMaxSize = endIndex - startIndex;
119                 URL url = new URL(path);
120                 HttpURLConnection conn = (HttpURLConnection) url.openConnection();
121                 conn.setRequestMethod("GET");
122                 conn.setConnectTimeout(5000);
123                 // 如果中間斷過,接着上次的位置繼續下載,聰慧文件中讀取上次下載的位置
124                 File file = new File(getFileName(path) + threadID + ".txt");
125                 if (file.exists() && file.length() > 0) {
126                     FileInputStream fis = new FileInputStream(file);
127                     BufferedReader bufr = new BufferedReader(new InputStreamReader(fis));
128                     String lastPosition = bufr.readLine();
129                     int lastPosition1 = Integer.parseInt(lastPosition);
130 
131                     //賦值給進度條位置
132                     pblastPosition = lastPosition1 - startIndex;
133                     // 改變一下startIndex的值
134                     startIndex = lastPosition1 + 1;
135                     System.out.println("線程id:" + threadID + "真實下載的位置:" + lastPosition + "-------" + endIndex);
136 
137                     bufr.close();
138                     fis.close();
139 
140                 }
141 
142                 conn.setRequestProperty("Range", "bytes=" + startIndex + "-" + endIndex);
143                 int code = conn.getResponseCode();
144                 if (code == 206) {
145                     // 隨機讀寫文件對象
146                     RandomAccessFile raf = new RandomAccessFile(getFileName(path), "rw");
147                     // 每個線程從自己的位置開始寫
148 
149                     raf.seek(startIndex);
150                     InputStream in = conn.getInputStream();
151                     // 把數據寫到文件中
152                     int len = -1;
153                     byte[] buffer = new byte[1024];
154                     int totle = 0;// 代表當前線程下載的大小
155                     while ((len = in.read(buffer)) != -1) {
156                         raf.write(buffer, 0, len);
157                         totle += len;
158 
159                         // 實現斷點續傳就是把當前線程下載的位置保存起來,下次再下載的時候按照上次下載的位置繼續下載
160                         int currentThreadPosition = startIndex + totle;// 存到一個txt文本中
161                         // 用來存儲當前線程當前下載的位置
162                         RandomAccessFile raff = new RandomAccessFile(getFileName(path) + threadID + ".txt", "rwd");
163                         raff.write(String.valueOf(currentThreadPosition).getBytes());
164                         raff.close();
165 
166                         //設置進度條當前的進度
167                         pbList.get(threadID).setMax(PbMaxSize);
168                         pbList.get(threadID).setProgress(pblastPosition + totle);
169                     }
170                     raf.close();
171                     System.out.println("線程ID:" + threadID + "下載完成");
172                     // 將產生的txt文件刪除,每個線程下載完成的具體時間不知道
173                     synchronized (DownLoadThread.class) {
174                         runningThread--;
175                         if (runningThread == 0) {
176                             //說明線程執行完畢
177                             for (int i = 0; i < threadCount; i++) {
178 
179                                 File filedel = new File(getFileName(path) + i + ".txt");
180                                 filedel.delete();
181                             }
182 
183                         }
184 
185                     }
186 
187                 }
188             } catch (MalformedURLException e) {
189                 // TODO Auto-generated catch block
190                 e.printStackTrace();
191             } catch (IOException e) {
192                 // TODO Auto-generated catch block
193                 e.printStackTrace();
194             }
195 
196         }
197     }
198 
199     public String getFileName(String path) {
200         int start = path.lastIndexOf("/") + 1;
201         String subString = path.substring(start);
202         String fileName = "/data/data/com.lgqrlchinese.heima76android_11_mutildownload/" + subString;
203         return fileName;
204 
205     }
206 }

在清單文件中添加以下權限

1     <uses-permission android:name="android.permission.INTERNET"/>
2     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

筆記結束

 

bug非常多,而且誰又願意寫這么繁瑣的邏輯,所以找到別人寫開源框架,下一篇將會作下筆記


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM