歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android開發多線程斷點續傳下載器

Android開發多線程斷點續傳下載器

日期:2017/3/1 11:17:00   编辑:Linux編程

使用多線程斷點續傳下載器在下載的時候多個線程並發可以占用服務器端更多資源,從而加快下載速度,在下載過程中記錄每個線程已拷貝數據的數量,如果下載中斷,比如無信號斷線、電量不足等情況下,這就需要使用到斷點續傳功能,下次啟動時從記錄位置繼續下載,可避免重復部分的下載。這裡采用數據庫來記錄下載的進度。

效果圖

斷點續傳

1.斷點續傳需要在下載過程中記錄每條線程的下載進度

2.每次下載開始之前先讀取數據庫,查詢是否有未完成的記錄,有就繼續下載,沒有則創建新記錄插入數據庫

3.在每次向文件中寫入數據之後,在數據庫中更新下載進度

4.下載完成之後刪除數據庫中下載記錄

Handler傳輸數據

這個主要用來記錄百分比,每下載一部分數據就通知主線程來記錄時間

1.主線程中創建的View只能在主線程中修改,其他線程只能通過和主線程通信,在主線程中改變View數據

2.我們使用Handler可以處理這種需求

主線程中創建Handler,重寫handleMessage()方法

新線程中使用Handler發送消息,主線程即可收到消息,並且執行handleMessage()方法

動態生成新View

可實現多任務下載

1.創建XML文件,將要生成的View配置好

2.獲取系統服務LayoutInflater,用來生成新的View

LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);

3.使用inflate(int resource, ViewGroup root)方法生成新的View

4.調用當前頁面中某個容器的addView,將新創建的View添加進來

示例

進度條樣式 download.xml

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout
  3. xmlns:Android="http://schemas.android.com/apk/res/android"
  4. android:layout_width="fill_parent"
  5. android:layout_height="wrap_content"
  6. >
  7. <LinearLayout
  8. android:orientation="vertical"
  9. android:layout_width="fill_parent"
  10. android:layout_height="wrap_content"
  11. android:layout_weight="1"
  12. >
  13. <!--進度條樣式默認為圓形進度條,水平進度條需要配置style屬性,
  14. ?android:attr/progressBarStyleHorizontal -->
  15. <ProgressBar
  16. android:layout_width="fill_parent"
  17. android:layout_height="20dp"
  18. style="?android:attr/progressBarStyleHorizontal"
  19. />
  20. <TextView
  21. android:layout_width="wrap_content"
  22. android:layout_height="wrap_content"
  23. android:layout_gravity="center"
  24. android:text="0%"
  25. />
  26. </LinearLayout>
  27. <Button
  28. android:layout_width="40dp"
  29. android:layout_height="40dp"
  30. android:onClick="pause"
  31. android:text="||"
  32. />
  33. </LinearLayout>
Copyright © Linux教程網 All Rights Reserved