Android 多線程斷點(diǎn)下載

Android 多線程斷點(diǎn)下載

概念

多線程斷點(diǎn)下載:意思是把一個下載文件分成多個置森,然后分配每個線程去下載分段,當(dāng)每個線程下載完成一段時候帐我,存儲他的下載量,如果當(dāng)網(wǎng)絡(luò)不好愧膀,或者斷開連接失敗拦键,那么下次從下載量開始地方下載,而不用重新下載檩淋。

技術(shù)難點(diǎn)

1芬为、線程分配下載

URL url = new URL(downUrl);
connection = (HttpURLConnection) url.openConnection();
connection.setReadTimeout(10 * 1000);
connection.setRequestMethod("GET");
int code = connection.getResponseCode();
if (code == 200) {
    int fileLength = connection.getContentLength();
    RandomAccessFile randomFile = new RandomAccessFile(new File(storePath), "rw");
    randomFile.setLength(fileLength);
    randomFile.close();
    blockSize = fileLength / threadCount;//得到分段大小

for (int i = 0; i < threadCount; i++) {
    int startBlock = i * blockSize;
    int endBlock = (i + 1) * blockSize - 1;
    if (i == threadCount - 1) {//如果是最后一個線程,下載完
        endBlock = fileLength - 1;
    }
   //下載邏輯.....
}
}

2蟀悦、這里主要是在網(wǎng)絡(luò)連接時候媚朦,分段的讀寫和分段的寫入

HttpURLConnection
.setRequestProperty("Range", "bytes=" + startBlock + "-" + endBlock);

startBlock是開始的下載點(diǎn),endBlock是下載結(jié)束的點(diǎn)熬芜。
3、存儲分段的文件下載量
我在這里使用文件的方式存儲福稳,你也可以使用其他方式涎拉,只有能持久化,就ok的圆,而且這里使用了線程多個文件鼓拧,你也可以使用單個文件存儲,按照行來存儲越妈。

File file = new File(storePath.substring(0, storePath.lastIndexOf("/")), version + "_" + threadId + ".txt");
RandomAccessFile downLoadAss = null;
if (file != null && file.exists()) {
    downLoadAss = new RandomAccessFile(file, "rwd");
    String lastPositon = downLoadAss.readLine();
    if (null == lastPositon || "".equals(lastPositon)) {
        this.startBlock = startBlock;
    } else {
        if (lastPositon != null && !"".equals(lastPositon)) {
            startBlock = Integer.parseInt(lastPositon) - 1;
        }
    }
} else {
    downLoadAss = new RandomAccessFile(file, "rwd");
}
....
while ((length = input.read(bytes)) != -1) {
    randomAccessFile.write(bytes, 0, length);
    total += length;
    downLoadAss.seek(0);
    downLoadAss.write(String.valueOf(startBlock + total).getBytes("UTF-8"));
}

存儲下載量的文件季俩,如果里面有值,讀取出來梅掠,然后重新設(shè)置起始點(diǎn),然后在寫入文件時候酌住,寫入讀取的數(shù)據(jù)量。

具體代碼實現(xiàn)


public class MutilDownHelper {
    private static int blockSize;
    private int currentRunThreadCount ;
    /**
     *
     * @param downUrl 下載地址
     * @param storePath 存儲地址
     * @param threadCount 線程池大小
     * @param version 下載版本
     * @return
     */
    public int  load(String downUrl, String storePath, int threadCount, String version) {
        HttpURLConnection connection = null;
        currentRunThreadCount = threadCount;
        try {
            URL url = new URL(downUrl);
            connection = (HttpURLConnection) url.openConnection();
            connection.setReadTimeout(10 * 1000);
            connection.setRequestMethod("GET");
            int code = connection.getResponseCode();
            if (code == 200) {
                int fileLength = connection.getContentLength();
                RandomAccessFile randomFile = new RandomAccessFile(new File(storePath), "rw");
                randomFile.setLength(fileLength);
                randomFile.close();
                blockSize = fileLength / threadCount;
                ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()+1);
                List<DownLoadThread> downLoadThreads = new ArrayList<>();
                for (int i = 0; i < threadCount; i++) {
                    int startBlock = i * blockSize;
                    int endBlock = (i + 1) * blockSize - 1;
                    if (i == threadCount - 1) {//如果是最后一個線程阎抒,下載完
                        endBlock = fileLength - 1;
                    }
                    downLoadThreads.add(new DownLoadThread(i, startBlock, endBlock, downUrl, storePath, version));
                }
                try {
                    List<Future<Integer>> futures = executorService.invokeAll(downLoadThreads);
                    for (Future<Integer> future : futures) {
                        if (future.get() == 1) {//這里會等待 阻塞線程 1是成功的標(biāo)識
                            currentRunThreadCount = currentRunThreadCount - 1;//還沒有完成的進(jìn)程
                        }
                    }
                    if (currentRunThreadCount == 0) {
                        return 1;
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                }
            }
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
        return 0;
    }


    public static class DownLoadThread implements Callable<Integer> {

        private int threadId;
        private int startBlock;
        private int endBlock;

        private String downUrl;
        private String storePath;
        private String version;//解決下載中斷,不同版本的切換問題


        public DownLoadThread(int i, int startBlock, int endBlock, String url, String storePath, String version) {
            this.threadId = i;
            this.startBlock = startBlock;
            this.endBlock = endBlock;
            this.downUrl = url;
            this.storePath = storePath;
            this.version = version;
        }

        @Override
        public Integer call() {
            try {
                URL url = new URL(downUrl);
                HttpURLConnection con = (HttpURLConnection) url.openConnection();
                con.setRequestMethod("GET");
                con.setConnectTimeout(10 * 1000);
                File file = new File(storePath.substring(0, storePath.lastIndexOf("/")), version + "_" + threadId + ".txt");
                RandomAccessFile downLoadAss = null;
                if (file != null && file.exists()) {
                    downLoadAss = new RandomAccessFile(file, "rwd");
                    String lastPositon = downLoadAss.readLine();
                    if (null == lastPositon || "".equals(lastPositon)) {
                        this.startBlock = startBlock;
                    } else {
                        if (lastPositon != null && !"".equals(lastPositon)) {
                            startBlock = Integer.parseInt(lastPositon) - 1;
                        }
                    }
                } else {
                    downLoadAss = new RandomAccessFile(file, "rwd");
                }
                con.setRequestProperty("Range", "bytes=" + startBlock + "-" + endBlock);
                if (con.getResponseCode() == 206) {//請求部分成果
                    InputStream input = con.getInputStream();
                    RandomAccessFile randomAccessFile = new RandomAccessFile(new File(storePath), "rwd");
                    randomAccessFile.seek(startBlock);
                    byte[] bytes = new byte[1024 * 4];
                    int length = -1;
                    int total = 0;
                    while ((length = input.read(bytes)) != -1) {
                        randomAccessFile.write(bytes, 0, length);
                        total += length;
                        downLoadAss.seek(0);
                        downLoadAss.write(String.valueOf(startBlock + total).getBytes("UTF-8"));
                    }
                    downLoadAss.close();
                    randomAccessFile.close();
                    input.close();
                    Log.e("show", "線程" + threadId + "下載關(guān)閉");
                    File f = new File(storePath.substring(0, storePath.lastIndexOf("/")), version + "_" + threadId + ".txt");
                    f.delete();//刪除記錄下載的文件
                    return 1;
                }
            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return 0;
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return 0;
            }
            return 1;

        }

    }

這里我的場景是等這個線程分段下載完成后需要判斷這些線程都寫完成了,所以使用了Callable,然后在Future里面去判斷是否都完成了颅眶,這也是一個比較難的點(diǎn)啊易。當(dāng)然如果你不需要這些判斷,你也可以把calable改寫成一個runable逞带。這樣實現(xiàn)也沒有問題欺矫,我這樣有一個好處,是我有返回值展氓,判斷我這個下載是否完成了穆趴,還是失敗了。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末遇汞,一起剝皮案震驚了整個濱河市毡代,隨后出現(xiàn)的幾起案子阅羹,更是在濱河造成了極大的恐慌,老刑警劉巖教寂,帶你破解...
    沈念sama閱讀 222,252評論 6 516
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件捏鱼,死亡現(xiàn)場離奇詭異,居然都是意外死亡酪耕,警方通過查閱死者的電腦和手機(jī)导梆,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,886評論 3 399
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來迂烁,“玉大人看尼,你說我怎么就攤上這事∶瞬剑” “怎么了藏斩?”我有些...
    開封第一講書人閱讀 168,814評論 0 361
  • 文/不壞的土叔 我叫張陵,是天一觀的道長却盘。 經(jīng)常有香客問我狰域,道長,這世上最難降的妖魔是什么黄橘? 我笑而不...
    開封第一講書人閱讀 59,869評論 1 299
  • 正文 為了忘掉前任兆览,我火速辦了婚禮,結(jié)果婚禮上塞关,老公的妹妹穿的比我還像新娘抬探。我一直安慰自己,他們只是感情好帆赢,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,888評論 6 398
  • 文/花漫 我一把揭開白布小压。 她就那樣靜靜地躺著,像睡著了一般椰于。 火紅的嫁衣襯著肌膚如雪场航。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 52,475評論 1 312
  • 那天廉羔,我揣著相機(jī)與錄音溉痢,去河邊找鬼。 笑死憋他,一個胖子當(dāng)著我的面吹牛孩饼,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播竹挡,決...
    沈念sama閱讀 41,010評論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼镀娶,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了揪罕?” 一聲冷哼從身側(cè)響起梯码,我...
    開封第一講書人閱讀 39,924評論 0 277
  • 序言:老撾萬榮一對情侶失蹤宝泵,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后轩娶,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體儿奶,經(jīng)...
    沈念sama閱讀 46,469評論 1 319
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,552評論 3 342
  • 正文 我和宋清朗相戀三年鳄抒,在試婚紗的時候發(fā)現(xiàn)自己被綠了闯捎。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,680評論 1 353
  • 序言:一個原本活蹦亂跳的男人離奇死亡许溅,死狀恐怖瓤鼻,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情贤重,我是刑警寧澤茬祷,帶...
    沈念sama閱讀 36,362評論 5 351
  • 正文 年R本政府宣布,位于F島的核電站并蝗,受9級特大地震影響祭犯,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜借卧,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 42,037評論 3 335
  • 文/蒙蒙 一盹憎、第九天 我趴在偏房一處隱蔽的房頂上張望筛峭。 院中可真熱鬧铐刘,春花似錦、人聲如沸影晓。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,519評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽挂签。三九已至疤祭,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間饵婆,已是汗流浹背勺馆。 一陣腳步聲響...
    開封第一講書人閱讀 33,621評論 1 274
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留侨核,地道東北人草穆。 一個月前我還...
    沈念sama閱讀 49,099評論 3 378
  • 正文 我出身青樓,卻偏偏與公主長得像搓译,于是被迫代替她去往敵國和親悲柱。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,691評論 2 361

推薦閱讀更多精彩內(nèi)容