Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 多執行緒下載器核心分享

編輯:關於 Android 開發

Android 多執行緒下載器核心分享

本文分享一個 Android 多執行緒下載器範例,重點在於使用多個執行緒下載同一個檔案,並透過 Handler 更新進度條。

Activity 邏輯

public class MultiThreadDown extends Activity {
    private EditText url;
    private Button downButton;
    private ProgressBar bar;
    private DownUtil downUtil;
    private int mDownStatus;
    private int threadNum = 6;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0x123) {
                bar.setProgress(mDownStatus);
                if (mDownStatus >= 100) {
                    Toast.makeText(MultiThreadDown.this, "下載完成", Toast.LENGTH_SHORT).show();
                }
            }
        }
    };
}

主畫面布局

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <EditText
        android:id="@+id/url"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/down"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="下載" />

    <ProgressBar
        android:id="@+id/bar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:max="100" />
</LinearLayout>

下載選項對話框

按下下載後,可先跳出對話框讓使用者確認儲存路徑與檔案名稱。

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <EditText
        android:id="@+id/editText_target_path"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <EditText
        android:id="@+id/editText_file_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</LinearLayout>

執行結果

輸入 URL 後按下下載,系統會先連線取得檔案資訊,再開始下載並顯示進度。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved