萌萌哒-多线程下载(断点续传)

MainActivity:

package top.mengmei219.multithreaddownload;

import android.content.Context;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.AttributeSet;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import top.mengmei219.multithreaddownload.util.ShareUtil;


public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    String sourceURL = "http://192.168.1.104:8080/itheima74/yuer.gif"; //资源链接固定
    String destPath = "/sdcard/Download/"; //下载资源存放目的地

    int threadCount; //线程数
    int size; //分段大小
    int finishThread = 0; //完成的线程数

    Context mContext;
    Handler mHandler = new Handler();
    EditText editText; //线程数
    LinearLayout progressLayout; //进度条Layout
    Map<Integer, ProgressBar> progressMap = new HashMap<Integer, ProgressBar>(); //存放progress

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mContext = this;

        //线程数
        editText = (EditText) findViewById(R.id.et_threadCount);
        int count = ShareUtil.getThreadCount(mContext); //回显线程数
        if (count != -1) {
            editText.setText(count);
        }

        //点击下载
        findViewById(R.id.btn_download).setOnClickListener(this);
        //进度条Layout
        progressLayout = (LinearLayout) findViewById(R.id.ll_progressLayout);
    }


    @Override
    public void onClick(View v) {
        //重新下载
        finishThread = 0;
        //获取用户指定的线程数
        threadCount = Integer.parseInt(editText.getText().toString().trim());

        //开启子线程请求服务器资源总大小
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    URL url = new URL(sourceURL); //资源链接
                    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                    urlConnection.setRequestMethod("GET");
                    urlConnection.setConnectTimeout(1000 * 10);

                    int code = urlConnection.getResponseCode();
                    if (code == 200) {
                        int contentLength = urlConnection.getContentLength(); //获取资源大小

                        //创建一个与资源同大的文件占为
                        RandomAccessFile random = new RandomAccessFile(new File(destPath + getFileName(sourceURL)), "rw");
                        random.setLength(contentLength);

                        //清空进度条父控件
                        mHandler.post(new Runnable() {
                            @Override
                            public void run() {
                                progressLayout.removeAllViews();
                                progressMap.clear();
                            }
                        });
                        //计算各线程分配
                        for (int threadID = 0; threadID < threadCount; threadID++) {
                            size = contentLength / threadCount; //分段大小
                            int startPosition = threadID * size; //起始位置
                            int endPosition = (threadID + 1) * size - 1; //结束位置
                            if (threadID == threadCount - 1) { //最后一个线程
                                endPosition = contentLength - 1;
                                size = contentLength / threadCount + contentLength % threadCount;
                            }
                            new MyThread(mHandler, threadID, startPosition, endPosition).start(); //开启自定义线程

                            //去主线程加载进度条
                            final int finalThreadID = threadID;
                            mHandler.post(new Runnable() {
                                @Override
                                public void run() {
                                    ProgressBar progress = (ProgressBar) View.inflate(mContext, R.layout.child_progress, null);
                                    progress.setMax(size);
                                    progressLayout.addView(progress);
                                    progressMap.put(finalThreadID, progress);
                                }
                            });
                        }
                    }
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }


    public String getFileName(String filePath) {
        return filePath.substring(filePath.lastIndexOf("/") + 1);
    }


    //自定义线程
    class MyThread extends Thread {

        private Handler responseHandler; //结果处理

        private int threadID; //线程ID
        private int startPosition; //起始位置
        private int endPosition; //结束位置


        public MyThread(Handler responseHandler, int threadID, int startPosition, int endPosition) {
            this.responseHandler = responseHandler;
            this.threadID = threadID;
            this.startPosition = startPosition;
            this.endPosition = endPosition;
            System.out.println("threadID " + threadID + ": " + startPosition + " - " + endPosition);
        }

        @Override
        public void run() {
            int lastPosition = startPosition;
            try {
                URL url = new URL(sourceURL); //资源链接
                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setRequestMethod("GET");
                urlConnection.setConnectTimeout(1000 * 10);

                //读取最后位置
                int position = ShareUtil.getLastPosition(mContext, threadID);
                if (position != -1) {
                    if (position > endPosition) position = endPosition;
                    lastPosition = position;
                    System.out.println("实际: threadID " + threadID + ": " + lastPosition + " - " + endPosition);
                }
                
                //分段请求头
                urlConnection.setRequestProperty("Range", "bytes=" + lastPosition + "-" + endPosition);

                int code = urlConnection.getResponseCode();
                //分段请求成功
                if (code == 206) {
                    InputStream inputStream = urlConnection.getInputStream();
                    byte[] buffer = new byte[1024 * 10];
                    int len = 0;

                    RandomAccessFile random = new RandomAccessFile(destPath + getFileName(sourceURL), "rw");
                    random.seek(lastPosition);

                    while ((len = inputStream.read(buffer)) > 0) {
                        random.write(buffer, 0, len);

                        Thread.sleep(50); //睡2毫秒,使进度条缓慢前进

                        //更新缓存指针
                        lastPosition = lastPosition + len;
                        ShareUtil.setLastPosition(mContext, threadID, lastPosition);

                        //去主线程更新进度条
                        final int finalLastPosition1 = lastPosition;
                        mHandler.post(new Runnable() {
                            @Override
                            public void run() {
                                progressMap.get(threadID).setProgress(finalLastPosition1 - startPosition);
                            }
                        });
                    }
                    inputStream.close();
                    random.close();
                }


                synchronized (MyThread.class) {
                    System.out.println(threadID + " - 下载完成!");
                    finishThread++;

                    if (finishThread == threadCount) {
                        System.out.println("全部下载完成,删掉临时文件!");

                        //界面提示
                        responseHandler.post(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(mContext, "全部下载完成!", Toast.LENGTH_LONG).show();
                            }
                        });

                        //删除临时文件
                        ShareUtil.setThreadCount(mContext, -1);
                        for (int i = 0; i < threadCount; i++) {
                            ShareUtil.setLastPosition(mContext, i, -1);
                        }
                    }
                }

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }


}

ShareUtil:

package top.mengmei219.multithreaddownload.util;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Build;
import android.preference.PreferenceManager;
import android.support.annotation.RequiresApi;


public class ShareUtil {

    public static int getLastPosition(Context context, int threadID){
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
        return sharedPreferences.getInt("lastPosition_thread"+threadID, -1);
    }

    public static boolean setLastPosition(Context context, int threadID, int position){
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        return editor.putInt("lastPosition_thread"+threadID, position).commit();
    }

    public static int getThreadCount(Context context){
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
        return sharedPreferences.getInt("multiDownLoad_threadCount", -1);
    }

    public static boolean setThreadCount(Context context, int threadCount){
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        return editor.putInt("multiDownLoad_threadCount", threadCount).commit();
    }

}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,242评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,769评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,484评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,133评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,007评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,080评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,496评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,190评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,464评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,549评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,330评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,205评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,567评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,889评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,160评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,475评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,650评论 2 335

推荐阅读更多精彩内容