5.2多線程斷點下載

1.首先在本地創建一個大小跟服務器一模一樣的空白文件。
2.開啓若干個子線程分別去下載對應的資源。

public class MainActivity extends Activity {
    protected static final int DOWNLOAD_ERROR = 1;//下載錯誤
    private static final int THREAD_ERROR = 2;//線程錯誤
    public static final int DWONLOAD_FINISH = 3;//下載成功
    private EditText et_path;//下載的路徑
    private EditText et_count;//下載的線程數量
    /**
     * 存放進度條的佈局
     */
    private LinearLayout ll_container;
    /**
     * 進度條的集合
     */
    private List<ProgressBar> pbs;
    /**
     * android下的消息處理器,在主線程創建,纔可以更新ui
     */
    private Handler handler = new Handler(){
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case DOWNLOAD_ERROR:
                Toast.makeText(getApplicationContext(), "下載失敗", 0).show();
                break;
            case THREAD_ERROR:
                Toast.makeText(getApplicationContext(), "下載失敗,請重試", 0).show();
                break;
            case DWONLOAD_FINISH:
                Toast.makeText(getApplicationContext(), "下載完成", 0).show();
                break;
            }
        };
    };

    /**
     * 線程的數量
     */
    private int threadCount = 3;
    /**
     * 每個下載區塊的大小
     */
    private long blocksize;
    /**
     * 正在運行的線程的數量
     */
    private  int runningThreadCount;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        et_path = (EditText) findViewById(R.id.et_path);
        et_count = (EditText) findViewById(R.id.et_count);
        ll_container = (LinearLayout) findViewById(R.id.ll_container);
    }

    /**
     * 下載按鈕的點擊事件
     * @param view
     */
    public void downLoad(View view){
        //獲得下載文件的路徑
        final String path = et_path.getText().toString().trim();
        if(TextUtils.isEmpty(path)){
            Toast.makeText(this, "對不起下載路徑不能爲空", 0).show();
            return;
        }
        //獲得下載線程數量
        String count = et_count.getText().toString().trim();
        if(TextUtils.isEmpty(path)){
            Toast.makeText(this, "對不起,線程數量不能爲空", 0).show();
            return;
        }
        threadCount = Integer.parseInt(count);
        //清空掉舊的進度條
        ll_container.removeAllViews();
        //在界面裏面添加count個進度條
        pbs = new ArrayList<ProgressBar>();
        for(int j=0;j<threadCount;j++){
            ProgressBar pb = (ProgressBar) View.inflate(this, R.layout.pb, null);
            ll_container.addView(pb);
            pbs.add(pb);
        }
        Toast.makeText(this, "開始下載", 0).show();
        new Thread(){
            public void run() {
                try {
                    URL url = new URL(path);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("GET");
                    conn.setConnectTimeout(5000);
                    int code = conn.getResponseCode();
                    if (code == 200) {
                        long size = conn.getContentLength();// 得到服務端返回的文件的大小
                        System.out.println("服務器文件的大小:" + size);
                        blocksize = size / threadCount;
                        // 1.首先在本地創建一個大小跟服務器一模一樣的空白文件。
                        File file = new File(Environment.getExternalStorageDirectory(),getFileName(path));
                        RandomAccessFile raf = new RandomAccessFile(file, "rw");
                        raf.setLength(size);
                        // 2.開啓若干個子線程分別去下載對應的資源。
                        runningThreadCount = threadCount;
                        for (int i = 1; i <= threadCount; i++) {
                            long startIndex = (i - 1) * blocksize;
                            long endIndex = i * blocksize - 1;
                            if (i == threadCount) {
                                // 最後一個線程
                                endIndex = size - 1;
                            }
                            System.out.println("開啓線程:" + i + "下載的位置:" + startIndex + "~"
                                    + endIndex);
                            int threadSize = (int) (endIndex - startIndex);
                            pbs.get(i-1).setMax(threadSize);
                            //創建並開始下載線程的方法
                            new DownloadThread(path, i, startIndex, endIndex).start();
                        }
                    }
                    conn.disconnect();
                } catch (Exception e) {
                    e.printStackTrace();
                    Message msg = Message.obtain();
                    msg.what = DOWNLOAD_ERROR;
                    handler.sendMessage(msg);
                }

            };
        }.start();

    }
    private class DownloadThread extends Thread {

        private int threadId;
        private long startIndex;
        private long endIndex;
        private String path;

        public DownloadThread(String path, int threadId, long startIndex,
                long endIndex) {
            this.path = path;
            this.threadId = threadId;
            this.startIndex = startIndex;
            this.endIndex = endIndex;
        }

        @Override
        public void run() {
            try {
                // 當前線程下載的總大小
                int total = 0;
                File positionFile = new File(Environment.getExternalStorageDirectory(),getFileName(path)+threadId + ".txt");
                URL url = new URL(path);
                HttpURLConnection conn = (HttpURLConnection) url
                        .openConnection();
                conn.setRequestMethod("GET");
                // 接着從上一次的位置繼續下載數據
                if (positionFile.exists() && positionFile.length() > 0) {// 判斷是否有記錄
                    FileInputStream fis = new FileInputStream(positionFile);
                    BufferedReader br = new BufferedReader(
                            new InputStreamReader(fis));
                    // 獲取當前線程上次下載的總大小是多少
                    String lasttotalstr = br.readLine();
                    int lastTotal = Integer.valueOf(lasttotalstr);
                    System.out.println("上次線程" + threadId + "下載的總大小:"
                            + lastTotal);
                    startIndex += lastTotal;
                    total += lastTotal;// 加上上次下載的總大小。
                    fis.close();
                    //存數據庫。
                    //_id path threadid total
                }

                conn.setRequestProperty("Range", "bytes=" + startIndex + "-"
                        + endIndex);

                conn.setConnectTimeout(5000);
                int code = conn.getResponseCode();
                System.out.println("code=" + code);
                InputStream is = conn.getInputStream();
                File file = new File(Environment.getExternalStorageDirectory(),getFileName(path));
                RandomAccessFile raf = new RandomAccessFile(file, "rw");
                // 指定文件開始寫的位置。
                raf.seek(startIndex);
                System.out.println("第" + threadId + "個線程:寫文件的開始位置:"
                        + String.valueOf(startIndex));
                int len = 0;
                byte[] buffer = new byte[1024];
                while ((len = is.read(buffer)) != -1) {
                    RandomAccessFile rf = new RandomAccessFile(positionFile,
                            "rwd");
                    raf.write(buffer, 0, len);
                    total += len;
                    rf.write(String.valueOf(total).getBytes());
                    rf.close();
                    pbs.get(threadId-1).setProgress(total);
                }
                is.close();
                raf.close();

            } catch (Exception e) {
                e.printStackTrace();
                Message msg = Message.obtain();
                msg.what = THREAD_ERROR;
                handler.sendMessage(msg);
            } finally {
                // 只有所有的線程都下載完畢後 纔可以刪除記錄文件。
                synchronized (MainActivity.class) {
                    System.out.println("線程" + threadId + "下載完畢了");
                    runningThreadCount--;
                    if (runningThreadCount < 1) {
                        System.out.println("所有的線程都工作完畢了。刪除臨時記錄的文件");
                        for (int i = 1; i <= threadCount; i++) {
                            File f = new File(Environment.getExternalStorageDirectory(),getFileName(path)+ i + ".txt");
                            System.out.println(f.delete());
                        }
                        Message msg = Message.obtain();
                        msg.what = DWONLOAD_FINISH;
                        handler.sendMessage(msg);
                    }
                }

            }
        }
    }
    private String getFileName(String path){
        int start = path.lastIndexOf("/")+1;
        return path.substring(start);
    }

}

pb.xml

<?xml version="1.0" encoding="utf-8"?>
<ProgressBar xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/progressBar1"
    style="?android:attr/progressBarStyleHorizontal"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" />

開源多線程下載:

public class MainActivity extends Activity {
    private EditText et_path;
    private TextView tv_info;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        et_path = (EditText) findViewById(R.id.et_path);
        tv_info = (TextView) findViewById(R.id.tv_info);
    }

    public void download(View view){
        String path = et_path.getText().toString().trim();
        if(TextUtils.isEmpty(path)){
            Toast.makeText(this, "請輸入下載的路徑", 0).show();
            return;
        }else{
            HttpUtils http = new HttpUtils();
            HttpHandler handler = http.download(path,
                    "/sdcard/xxx.zip",
                    true, // 如果目標文件存在,接着未完成的部分繼續下載。服務器不支持RANGE時將從新下載。
                    true, // 如果從請求返回信息中獲取到文件名,下載完成後自動重命名。
                    new RequestCallBack<File>() {

                        @Override
                        public void onStart() {
                            tv_info.setText("conn...");
                        }

                        @Override
                        public void onLoading(long total, long current, boolean isUploading) {
                            tv_info.setText(current + "/" + total);
                        }

                        @Override
                        public void onSuccess(ResponseInfo<File> responseInfo) {
                            tv_info.setText("downloaded:" + responseInfo.result.getPath());
                        }
                        @Override
                        public void onFailure(HttpException error, String msg) {
                            tv_info.setText(msg);
                        }
                });
        }
    }
}

開源需要導包xUtils

發佈了50 篇原創文章 · 獲贊 14 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章