1. 程式人生 > 程式設計 >Android多執行緒斷點續傳下載實現程式碼

Android多執行緒斷點續傳下載實現程式碼

學習了多執行緒下載,而且可以斷點續傳的邏輯,執行緒數量可以自己選擇,但是執行緒數量過多手機就承受不起,導致閃退,好在有斷點續傳。

步驟寫在了程式碼的註釋裡。大概就是獲取伺服器檔案的大小,在本地新建一個相同大小的檔案用來申請空間,然後將伺服器的檔案讀下來寫到申請的檔案中去。若開多執行緒,將檔案分塊,計算每個執行緒下載的開始位置和結束位置。若斷點傳輸,則儲存斷開後下載的位置,下次將此位置賦給開始下載的位置即可。細節見程式碼。

下面是效果圖:

Android多執行緒斷點續傳下載實現程式碼

佈局檔案activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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"
  tools:context=".MainActivity">

  <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <EditText
      android:id="@+id/et_path"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:hint="請輸入下載路徑"
      android:text="http://10.173.29.234/test.exe" />

    <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:background="#455eee"
      android:orientation="vertical">

    </LinearLayout>
  </LinearLayout>

</android.support.constraint.ConstraintLayout>

建立佈局檔案,用來動態顯示每個執行緒的進度條

layout.xml:

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

MainActivity.java:

import...;

public class MainActivity extends AppCompatActivity {

  private EditText et_path;
  private EditText et_threadCount;
  private LinearLayout ll_pb;
  private String path;

  private static int runningThread;// 代表正在執行的執行緒
  private int threadCount;
  private List<ProgressBar> pbList;//集合儲存進度條的引用

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

    et_path = findViewById(R.id.et_path);
    et_threadCount = findViewById(R.id.et_threadCount);
    ll_pb = findViewById(R.id.ll_pb);
    //新增一個進度條的引用
    pbList = new ArrayList<ProgressBar>();
  }

  //點選按鈕實現下載邏輯
  public void click(View view) {
    //獲取下載路徑
    path = et_path.getText().toString().trim();
    //獲取執行緒數量
    String threadCounts = et_threadCount.getText().toString().trim();
    //移除以前的進度條新增新的進度條
    ll_pb.removeAllViews();
    threadCount = Integer.parseInt(threadCounts);
    pbList.clear();
    for (int i = 0; i < threadCount; i++) {
      ProgressBar v = (ProgressBar) View.inflate(getApplicationContext(),R.layout.layout,null);

      //把v新增到幾何中
      pbList.add(v);

      //動態獲取進度條
      ll_pb.addView(v);
    }

    //java邏輯移植
    new Thread() {
      @Override
      public void run() {
        /*************/
        System.out.println("你好");
        try {
          URL url = new URL(path);
          HttpURLConnection conn = (HttpURLConnection) url.openConnection();
          conn.setRequestMethod("GET");
          conn.setConnectTimeout(5000);
          int code = conn.getResponseCode();
          if (code == 200) {
            int length = conn.getContentLength();
            // 把執行執行緒的數量賦值給runningThread
            runningThread = threadCount;

            System.out.println("length=" + length);
            // 建立一個和伺服器的檔案一樣大小的檔案,提前申請空間
            RandomAccessFile randomAccessFile = new RandomAccessFile(getFileName(path),"rw");
            randomAccessFile.setLength(length);
            // 算出每個執行緒下載的大小
            int blockSize = length / threadCount;
            // 計算每個執行緒下載的開始位置和結束位置
            for (int i = 0; i < length; i++) {
              int startIndex = i * blockSize;// 開始位置
              int endIndex = (i + 1) * blockSize;// 結束位置
              // 特殊情況就是最後一個執行緒
              if (i == threadCount - 1) {
                // 說明是最後一個執行緒
                endIndex = length - 1;
              }
              // 開啟執行緒去伺服器下載
              DownLoadThread downLoadThread = new DownLoadThread(startIndex,endIndex,i);
              downLoadThread.start();

            }

          }
        } catch (MalformedURLException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        } catch (IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
        /*************/
      }
    }.start();

  }

  private class DownLoadThread extends Thread {
    // 通過構造方法吧每個執行緒的開始位置和結束位置傳進來
    private int startIndex;
    private int endIndex;
    private int threadID;
    private int PbMaxSize;//代表當前下載(進度條)的最大值
    private int pblastPosition;//如果中斷過,這是進度條上次的位置

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

    }

    @Override
    public void run() {
      // 實現去伺服器下載檔案
      try {
        //計算進度條最大值
        PbMaxSize = endIndex - startIndex;
        URL url = new URL(path);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setConnectTimeout(5000);
        // 如果中間斷過,接著上次的位置繼續下載,聰慧檔案中讀取上次下載的位置
        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 lastPosition = bufr.readLine();
          int lastPosition1 = Integer.parseInt(lastPosition);

          //賦值給進度條位置
          pblastPosition = lastPosition1 - startIndex;
          // 改變一下startIndex的值
          startIndex = lastPosition1 + 1;
          System.out.println("執行緒id:" + threadID + "真實下載的位置:" + lastPosition + "-------" + endIndex);

          bufr.close();
          fis.close();

        }

        conn.setRequestProperty("Range","bytes=" + startIndex + "-" + endIndex);
        int code = conn.getResponseCode();
        if (code == 206) {
          // 隨機讀寫檔案物件
          RandomAccessFile raf = new RandomAccessFile(getFileName(path),"rw");
          // 每個執行緒從自己的位置開始寫

          raf.seek(startIndex);
          InputStream in = conn.getInputStream();
          // 把資料寫到檔案中
          int len = -1;
          byte[] buffer = new byte[1024];
          int totle = 0;// 代表當前執行緒下載的大小
          while ((len = in.read(buffer)) != -1) {
            raf.write(buffer,len);
            totle += len;

            // 實現斷點續傳就是把當前執行緒下載的位置儲存起來,下次再下載的時候按照上次下載的位置繼續下載
            int currentThreadPosition = startIndex + totle;// 存到一個txt文字中
            // 用來儲存當前執行緒當前下載的位置
            RandomAccessFile raff = new RandomAccessFile(getFileName(path) + threadID + ".txt","rwd");
            raff.write(String.valueOf(currentThreadPosition).getBytes());
            raff.close();

            //設定進度條當前的進度
            pbList.get(threadID).setMax(PbMaxSize);
            pbList.get(threadID).setProgress(pblastPosition + totle);
          }
          raf.close();
          System.out.println("執行緒ID:" + threadID + "下載完成");
          // 將產生的txt檔案刪除,每個執行緒下載完成的具體時間不知道
          synchronized (DownLoadThread.class) {
            runningThread--;
            if (runningThread == 0) {
              //說明執行緒執行完畢
              for (int i = 0; i < threadCount; i++) {

                File filedel = new File(getFileName(path) + i + ".txt");
                filedel.delete();
              }

            }

          }

        }
      } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }

    }
  }

  public String getFileName(String path) {
    int start = path.lastIndexOf("/") + 1;
    String subString = path.substring(start);
    String fileName = "/data/data/com.lgqrlchinese.heima76android_11_mutildownload/" + subString;
    return fileName;

  }
}

在清單檔案中新增以下許可權

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

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。