Android多線程斷點(diǎn)續(xù)傳下載實(shí)現(xiàn)代碼
學(xué)習(xí)了多線程下載,而且可以斷點(diǎn)續(xù)傳的邏輯,線程數(shù)量可以自己選擇,但是線程數(shù)量過多手機(jī)就承受不起,導(dǎo)致閃退,好在有斷點(diǎn)續(xù)傳。
步驟寫在了代碼的注釋里。大概就是獲取服務(wù)器文件的大小,在本地新建一個(gè)相同大小的文件用來申請(qǐng)空間,然后將服務(wù)器的文件讀下來寫到申請(qǐng)的文件中去。若開多線程,將文件分塊,計(jì)算每個(gè)線程下載的開始位置和結(jié)束位置。若斷點(diǎn)傳輸,則保存斷開后下載的位置,下次將此位置賦給開始下載的位置即可。細(xì)節(jié)見代碼。
下面是效果圖:
布局文件activity_main.xml:
<?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <EditText android:id="@+id/et_path" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="請(qǐng)輸入下載路徑" android:text="http://10.173.29.234/test.exe" /> <EditText android:id="@+id/et_threadCount" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="請(qǐng)輸入線程數(shù)量" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="click" android:text="下載" /> <LinearLayout android:id="@+id/ll_pb" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#455eee" android:orientation="vertical"> </LinearLayout> </LinearLayout> </android.support.constraint.ConstraintLayout>
創(chuàng)建布局文件,用來動(dòng)態(tài)顯示每個(gè)線程的進(jìn)度條
layout.xml:
<?xml version="1.0" encoding="utf-8"?> <ProgressBar xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/progressBar" style="?android:attr/progressBarStyleHorizontal" android:layout_width="match_parent" android:layout_height="wrap_content" />
MainActivity.java:
import...; public class MainActivity extends AppCompatActivity { private EditText et_path; private EditText et_threadCount; private LinearLayout ll_pb; private String path; private static int runningThread;// 代表正在運(yùn)行的線程 private int threadCount; private List<ProgressBar> pbList;//集合存儲(chǔ)進(jìn)度條的引用 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); et_path = findViewById(R.id.et_path); et_threadCount = findViewById(R.id.et_threadCount); ll_pb = findViewById(R.id.ll_pb); //添加一個(gè)進(jìn)度條的引用 pbList = new ArrayList<ProgressBar>(); } //點(diǎn)擊按鈕實(shí)現(xiàn)下載邏輯 public void click(View view) { //獲取下載路徑 path = et_path.getText().toString().trim(); //獲取線程數(shù)量 String threadCounts = et_threadCount.getText().toString().trim(); //移除以前的進(jìn)度條添加新的進(jìn)度條 ll_pb.removeAllViews(); threadCount = Integer.parseInt(threadCounts); pbList.clear(); for (int i = 0; i < threadCount; i++) { ProgressBar v = (ProgressBar) View.inflate(getApplicationContext(), R.layout.layout, null); //把v添加到幾何中 pbList.add(v); //動(dòng)態(tài)獲取進(jìn)度條 ll_pb.addView(v); } //java邏輯移植 new Thread() { @Override public void run() { /*************/ System.out.println("你好"); try { URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setConnectTimeout(5000); int code = conn.getResponseCode(); if (code == 200) { int length = conn.getContentLength(); // 把運(yùn)行線程的數(shù)量賦值給runningThread runningThread = threadCount; System.out.println("length=" + length); // 創(chuàng)建一個(gè)和服務(wù)器的文件一樣大小的文件,提前申請(qǐng)空間 RandomAccessFile randomAccessFile = new RandomAccessFile(getFileName(path), "rw"); randomAccessFile.setLength(length); // 算出每個(gè)線程下載的大小 int blockSize = length / threadCount; // 計(jì)算每個(gè)線程下載的開始位置和結(jié)束位置 for (int i = 0; i < length; i++) { int startIndex = i * blockSize;// 開始位置 int endIndex = (i + 1) * blockSize;// 結(jié)束位置 // 特殊情況就是最后一個(gè)線程 if (i == threadCount - 1) { // 說明是最后一個(gè)線程 endIndex = length - 1; } // 開啟線程去服務(wù)器下載 DownLoadThread downLoadThread = new DownLoadThread(startIndex, endIndex, i); downLoadThread.start(); } } } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } /*************/ } }.start(); } private class DownLoadThread extends Thread { // 通過構(gòu)造方法吧每個(gè)線程的開始位置和結(jié)束位置傳進(jìn)來 private int startIndex; private int endIndex; private int threadID; private int PbMaxSize;//代表當(dāng)前下載(進(jìn)度條)的最大值 private int pblastPosition;//如果中斷過,這是進(jìn)度條上次的位置 public DownLoadThread(int startIndex, int endIndex, int threadID) { this.startIndex = startIndex; this.endIndex = endIndex; this.threadID = threadID; } @Override public void run() { // 實(shí)現(xiàn)去服務(wù)器下載文件 try { //計(jì)算進(jìn)度條最大值 PbMaxSize = endIndex - startIndex; URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setConnectTimeout(5000); // 如果中間斷過,接著上次的位置繼續(xù)下載,聰慧文件中讀取上次下載的位置 File file = new File(getFileName(path) + threadID + ".txt"); if (file.exists() && file.length() > 0) { FileInputStream fis = new FileInputStream(file); BufferedReader bufr = new BufferedReader(new InputStreamReader(fis)); String lastPosition = bufr.readLine(); int lastPosition1 = Integer.parseInt(lastPosition); //賦值給進(jìn)度條位置 pblastPosition = lastPosition1 - startIndex; // 改變一下startIndex的值 startIndex = lastPosition1 + 1; System.out.println("線程id:" + threadID + "真實(shí)下載的位置:" + lastPosition + "-------" + endIndex); bufr.close(); fis.close(); } conn.setRequestProperty("Range", "bytes=" + startIndex + "-" + endIndex); int code = conn.getResponseCode(); if (code == 206) { // 隨機(jī)讀寫文件對(duì)象 RandomAccessFile raf = new RandomAccessFile(getFileName(path), "rw"); // 每個(gè)線程從自己的位置開始寫 raf.seek(startIndex); InputStream in = conn.getInputStream(); // 把數(shù)據(jù)寫到文件中 int len = -1; byte[] buffer = new byte[1024]; int totle = 0;// 代表當(dāng)前線程下載的大小 while ((len = in.read(buffer)) != -1) { raf.write(buffer, 0, len); totle += len; // 實(shí)現(xiàn)斷點(diǎn)續(xù)傳就是把當(dāng)前線程下載的位置保存起來,下次再下載的時(shí)候按照上次下載的位置繼續(xù)下載 int currentThreadPosition = startIndex + totle;// 存到一個(gè)txt文本中 // 用來存儲(chǔ)當(dāng)前線程當(dāng)前下載的位置 RandomAccessFile raff = new RandomAccessFile(getFileName(path) + threadID + ".txt", "rwd"); raff.write(String.valueOf(currentThreadPosition).getBytes()); raff.close(); //設(shè)置進(jìn)度條當(dāng)前的進(jìn)度 pbList.get(threadID).setMax(PbMaxSize); pbList.get(threadID).setProgress(pblastPosition + totle); } raf.close(); System.out.println("線程ID:" + threadID + "下載完成"); // 將產(chǎn)生的txt文件刪除,每個(gè)線程下載完成的具體時(shí)間不知道 synchronized (DownLoadThread.class) { runningThread--; if (runningThread == 0) { //說明線程執(zhí)行完畢 for (int i = 0; i < threadCount; i++) { File filedel = new File(getFileName(path) + i + ".txt"); filedel.delete(); } } } } } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public String getFileName(String path) { int start = path.lastIndexOf("/") + 1; String subString = path.substring(start); String fileName = "/data/data/com.lgqrlchinese.heima76android_11_mutildownload/" + subString; return fileName; } }
在清單文件中添加以下權(quán)限
<uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
利用Android實(shí)現(xiàn)一種點(diǎn)贊動(dòng)畫效果的全過程
最近做項(xiàng)目需要實(shí)現(xiàn)點(diǎn)贊動(dòng)畫,下面這篇文章主要給大家介紹了關(guān)于利用Android實(shí)現(xiàn)一種點(diǎn)贊動(dòng)畫效果的相關(guān)資料,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-12-12Android動(dòng)態(tài)修改ToolBar的Menu菜單示例
本篇文章主要介紹了Android動(dòng)態(tài)修改ToolBar的Menu菜單示例,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-02-02Android OpenGL ES 實(shí)現(xiàn)抖音傳送帶特效(原理解析)
這篇文章主要介紹了Android OpenGL ES 實(shí)現(xiàn)抖音傳送帶特效,抖音傳送帶特效推出已經(jīng)很長一段時(shí)間了,前面也實(shí)現(xiàn)了下,最近把它整理出來了,如果你有仔細(xì)觀測(cè)傳送帶特效,就會(huì)發(fā)現(xiàn)它的實(shí)現(xiàn)原理其實(shí)很簡單,需要的朋友可以參考下2022-07-07Android自定義組件獲取本地圖片和相機(jī)拍照?qǐng)D片
這篇文章主要為大家詳細(xì)介紹了Android自定義組件獲取本地圖片和相機(jī)拍照?qǐng)D片的相關(guān)資料,非常炫酷的效果,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-01-01Android 中HttpURLConnection與HttpClient使用的簡單實(shí)例
這篇文章介紹了Android 中HttpURLConnection與HttpClient使用的簡單實(shí)例,有需要的朋友可以參考一下2013-10-10Kotlin使用滾動(dòng)控件RecyclerView實(shí)例教程
RecyclerView是Android一個(gè)更強(qiáng)大的控件,其不僅可以實(shí)現(xiàn)和ListView同樣的效果,還有優(yōu)化了ListView中的各種不足。其可以實(shí)現(xiàn)數(shù)據(jù)縱向滾動(dòng),也可以實(shí)現(xiàn)橫向滾動(dòng)(ListView做不到橫向滾動(dòng))。接下來講解RecyclerView的用法2022-12-12Android運(yùn)用BroadcastReceiver實(shí)現(xiàn)強(qiáng)制下線
本篇文章主要介紹了Android運(yùn)用BroadcastReceiver實(shí)現(xiàn)強(qiáng)制下線,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-07-07