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

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 progressMap = new HashMap(); //存放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();
    }

}

你可能感兴趣的:(萌萌哒-多线程下载(断点续传))