1. 程式人生 > >Android的斷點續傳的下載線上檔案示例

Android的斷點續傳的下載線上檔案示例

Android的斷點續傳的下載線上檔案示例

檔案的結構如下:

activity_main.xml:
<LinearLayout 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"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <EditText
        android:id="@+id/et_path"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="http://192.168.159.1:8080/gh.zip"
        android:hint="請輸入下載路徑"
        tools:ignore="HardcodedText" />

    <EditText
        android:id="@+id/et_threadCount"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="請輸入執行緒的數量" />

    <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:orientation="vertical" >
    </LinearLayout>

</LinearLayout>
item.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="match_parent"
    android:layout_height="wrap_content" />
network_security_config.xml:
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <base-config cleartextTrafficPermitted="true" />
</network-security-config>
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.administrator.fdtest">

    <uses-permission android:name="android.permission.INTERNET"></uses-permission>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"></uses-permission>

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

    <application
        android:usesCleartextTraffic="true"
        android:networkSecurityConfig="@xml/network_security_config"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
MainActivity:
package com.example.administrator.fdtest;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.support.v4.app.ActivityCompat;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;

public class MainActivity extends Activity {

    private EditText et_path;
    private EditText et_threadCount;
    private LinearLayout ll_pb_layout;
    private String path;
    private static int runningThread;  //代表當前正在執行的執行緒
    private int threadCount;
    private List<ProgressBar> pbLists; //用來存進度條的引用


    private  final int REQUEST_EXTERNAL_STORAGE = 1;
    private  String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE };
    public  void verifyStoragePermissions(Activity activity) {
        // Check if we have write permission
        int permission = ActivityCompat.checkSelfPermission(activity,
                Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (permission != PackageManager.PERMISSION_GRANTED) {
            // We don't have permission so prompt the user
            ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE,
                    REQUEST_EXTERNAL_STORAGE);
        }
    }




    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        verifyStoragePermissions(this);
        // [1]找到我們關心的控制元件

        et_path = (EditText) findViewById(R.id.et_path);
        et_threadCount = (EditText) findViewById(R.id.et_threadCount);
        ll_pb_layout = (LinearLayout) findViewById(R.id.ll_pb);

        //[2]新增一個集合 用來存進度條的引用
        pbLists = new ArrayList<ProgressBar>();

    }

    //點選按鈕實現下載的邏輯
    public void click(View v){

        //[2]獲取下載的路徑

//        path = et_path.getText().toString().trim();
        path = "http://192.168.159.1:8080/gh.zip";

        //[3]獲取執行緒的數量
        String threadCountt  = et_threadCount.getText().toString().trim();
        //[3.0]先移除進度條 在新增
        ll_pb_layout.removeAllViews();

        threadCount = Integer.parseInt(threadCountt);
        pbLists.clear();
        for (int i = 0; i < threadCount; i++) {

            //[3.1]把我定義的item佈局轉換成一個view物件
            ProgressBar pbView = (ProgressBar) View.inflate(getApplicationContext(), R.layout.item, null);

            //[3.2]把pbView 新增到集合中
            pbLists.add(pbView);

            //[4]動態的新增進度條
            ll_pb_layout.addView(pbView);

        }


        //[5]開始移植   聯網 獲取檔案長度
        new Thread(){public void run() {

            //[一 ☆☆☆☆]獲取伺服器檔案的大小   要計算每個執行緒下載的開始位置和結束位置

            try {

                //(1) 建立一個url物件 引數就是網址
                URL url = new URL(path);
                //(2)獲取HttpURLConnection 連結物件
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                //(3)設定引數  傳送get請求
                conn.setRequestMethod("GET"); //預設請求 就是get  要大寫
                //(4)設定連結網路的超時時間
                conn.setConnectTimeout(5000);
                //(5)獲取伺服器返回的狀態碼
                int code = conn.getResponseCode(); //200  代表獲取伺服器資源全部成功  206請求部分資源
                if (code == 200) {

                    //(6)獲取伺服器檔案的大小
                    int length = conn.getContentLength();

                    //[6.1]把執行緒的數量賦值給正在執行的執行緒
                    runningThread = threadCount;


                    System.out.println("length:"+length);

                    //[二☆☆☆☆ ] 建立一個大小和伺服器一模一樣的檔案 目的提前把空間申請出來
                    RandomAccessFile rafAccessFile = new RandomAccessFile(getFilename(path), "rw");
                    rafAccessFile.setLength(length);

                    //(7)算出每個執行緒下載的大小
                    int blockSize = length /threadCount;

                    //[三☆☆☆☆  計算每個執行緒下載的開始位置和結束位置 ]
                    for (int i = 0; i < threadCount; i++) {
                        int startIndex = i * blockSize;   //每個執行緒下載的開始位置
                        int endIndex = (i+1)*blockSize - 1;
                        //特殊情況 就是最後一個執行緒
                        if (i == threadCount - 1) {
                            //說明是最後一個執行緒
                            endIndex = length - 1;

                        }

                        System.out.println("執行緒id:::"+i + "理論下載的位置"+":"+startIndex+"-----"+endIndex);

                        //四 開啟執行緒去伺服器下載檔案
                        DownLoadThread downLoadThread = new DownLoadThread(startIndex, endIndex, i);
                        downLoadThread.start();

                    }



                }

            } catch (Exception e) {
                e.printStackTrace();
            }
 
        };}.start();
    }


    //定義執行緒去伺服器下載檔案
    private  class DownLoadThread extends Thread{
        //通過構造方法把每個執行緒下載的開始位置和結束位置傳遞進來

        private int startIndex;
        private int endIndex;
        private int threadId;

        private int PbMaxSize; //代表當前執行緒下載的最大值
        //如果中斷過  獲取上次下載的位置
        private int pblastPostion;

        public DownLoadThread(int startIndex,int endIndex,int threadId){
            this.startIndex = startIndex;
            this.endIndex  = endIndex;
            this.threadId = threadId;
        }

        @Override
        public void run() {
            //四  實現去伺服器下載檔案的邏輯

            try {
                //(0)計算當前進度條的最大值
                PbMaxSize = endIndex - startIndex;
                //(1) 建立一個url物件 引數就是網址
                URL url = new URL(path);
                //(2)獲取HttpURLConnection 連結物件
                HttpURLConnection conn = (HttpURLConnection) url
                        .openConnection();
                //(3)設定引數  傳送get請求
                conn.setRequestMethod("GET"); //預設請求 就是get  要大寫
                //(4)設定連結網路的超時時間
                conn.setConnectTimeout(5000);


                //[4.0]如果中間斷過  繼續上次的位置 繼續下載   從檔案中讀取上次下載的位置

                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 lastPositionn = bufr.readLine();  //讀取出來的內容就是上一次下載的位置
                    int lastPosition = Integer.parseInt(lastPositionn);

                    //[4.0]給我們定義的進度條條位置 賦值
                    pblastPostion = lastPosition - startIndex;

                    //[4.0.1]要改變一下 startIndex 位置
                    startIndex = lastPosition + 1;

                    System.out.println("執行緒id::"+threadId + "真實下載的位置"+":"+startIndex+"-----"+endIndex);

                    fis.close(); //關閉流
                }

                //[4.1]設定一個請求頭Range (作用告訴伺服器每個執行緒下載的開始位置和結束位置)
                conn.setRequestProperty("Range", "bytes="+startIndex+"-"+endIndex);

                //(5)獲取伺服器返回的狀態碼
                int code = conn.getResponseCode(); //200  代表獲取伺服器資源全部成功  206請求部分資源 成功
                if (code == 206) {
                    //[6]建立隨機讀寫檔案物件
                    RandomAccessFile raf = new RandomAccessFile(getFilename(path), "rw");
                    //[6]每個執行緒要從自己的位置開始寫
                    raf.seek(startIndex);

                    InputStream in = conn.getInputStream(); //存的是feiq.exe

                    //[7]把資料寫到檔案中
                    int len = -1;
                    byte[] buffer = new byte[1024*1024];//1Mb

                    int total = 0; //代表當前執行緒下載的大小

                    while((len = in.read(buffer))!=-1){
                        raf.write(buffer, 0, len);

                        total +=len;
                        //[8]實現斷點續傳 就是把當前執行緒下載的位置 給存起來 下次再下載的時候 就是按照上次下載的位置繼續下載 就可以了
                        int currentThreadPosition =  startIndex + total;  //比如就存到一個普通的.txt文字中

                        //[9]用來存當前執行緒下載的位置
                        RandomAccessFile raff = new RandomAccessFile(getFilename(path)+threadId+".txt", "rwd");
                        raff.write(String.valueOf(currentThreadPosition).getBytes());
                        raff.close();

                        //[10]設定一下當前進度條的最大值 和 當前進度
                        pbLists.get(threadId).setMax(PbMaxSize);//設定進度條的最大值
                        pbLists.get(threadId).setProgress(pblastPostion+total);//設定當前進度條的當前進度
                    }
                    raf.close();//關閉流  釋放資源

                    System.out.println("執行緒id:"+threadId + "---下載完畢了");

                    //[10]把.txt檔案刪除  每個執行緒具體什麼時候下載完畢了 我們不知道

                    synchronized (DownLoadThread.class) {
                        runningThread--;
                        if (runningThread == 0) {
                            //說明所有的執行緒都執行完畢了 就把.txt檔案刪除
                            for (int i = 0; i < threadCount; i++) {
                                File  delteFile = new File(getFilename(path)+i+".txt");
                                delteFile.delete();
                            }
                        }
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    //獲取檔案的名字    "http://192.168.11.73:8080/feiq.exe";
    public  String getFilename(String path){

        int start =  path.lastIndexOf("/")+1;
        String substring = path.substring(start);

        String fileName = Environment.getExternalStorageDirectory().getPath()+"/"+substring;
        return fileName;
    }
}