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

Android 用 ProgressBar 即時顯示下載進度詳解

編輯:關於 Android 程式設計

下載檔案時當然要讓使用者看到進度。這個範例用 ProgressBar 搭配子執行緒,把下載百分比即時反映到介面上。過程中會踩到四個新手常碰到的問題,正好一起說明。

問題清單:

1、主執行緒中不能開啟網路連線,Toast 等也必須在主執行緒使用。

2、子執行緒不能直接修改 UI。

3、需要宣告網路權限。

4、暫停與繼續下載。

一、佈局檔 fragment_main

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.dragon.android.textbar.MainActivity$PlaceholderFragment" >

    <!-- progress 為當前進度;indeterminate 表示不確定模式,預設 false -->
    <ProgressBar
        android:id="@+id/progressBar1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:max="100"
        android:progress="0"
        android:indeterminate="true"/>

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:onClick="startLoad"
        android:layout_marginTop="86dp"
        android:background="#009FEE"
        android:text="@string/start"
        android:textColor="#ffffff" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/progressBar1"
        android:background="@null"
        android:layout_alignParentLeft="true" />
</RelativeLayout>

二、strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">hwdownload</string>
    <string name="hello_world">Hello world!</string>
    <string name="action_settings">Settings</string>
    <string name="start">開始</string>
    <string name="stop">暫停</string>
    <string name="contin">繼續</string>
</resources>

三、網路權限(問題 3)

在 AndroidManifest.xml 中補上:

<!-- 請求網絡權限 -->
<uses-permission android:name="android.permission.INTERNET"/>

少了這行,連線會直接拋出 UnknownHostException,而且是執行期才爆,編譯階段完全看不出來。

四、MainActivity(問題 1、2)

package com.dragon.android.textbar;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 只有建立某個 View 的執行緒才能改變該 View 的 UI,主執行緒也稱 UI 執行緒
 */
public class MainActivity extends Activity {

    private ProgressBar progressBar1;
    private Button button1;
    private TextView textView1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_main);
        progressBar1 = (ProgressBar) findViewById(R.id.progressBar1);
        button1 = (Button) findViewById(R.id.button1);
        textView1 = (TextView) findViewById(R.id.textView1);
    }

    public void startLoad(View view) {
        String text = (String) button1.getText();
        button1.setText(text.equals(getResources().getString(R.string.start))
                ? R.string.stop
                : (text.equals(getResources().getString(R.string.stop))
                    ? R.string.contin : R.string.stop));
        progressBar1.setIndeterminate(false);

        new Thread(new Runnable() {
            private int percent;

            @Override
            public void run() {
                try {
                    // 開啟 URL 必須在子執行緒
                    URL url = new URL(
                            "https://b.zol-img.com.cn/sjbizhi/images/9/540x960/1472549276394.jpg");
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    int contentLength = conn.getContentLength();

                    if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                        InputStream is = conn.getInputStream();
                        byte[] buffer = new byte[1024];
                        int len = -1;
                        int sum = 0;

                        while ((len = is.read(buffer)) != -1) {
                            sum += len;
                            // 注意轉型方式,否則整數除法會讓結果一直是 0
                            percent = (int) (100.0 * sum / contentLength);

                            // 切回主執行緒更新 UI
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    progressBar1.setProgress(percent);
                                    textView1.setText(percent + "%");
                                    if (percent == progressBar1.getMax()) {
                                        Toast.makeText(MainActivity.this, "下載完成!",
                                                Toast.LENGTH_SHORT).show();
                                    }
                                }
                            });
                        }
                        is.close();
                        conn.disconnect();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}

關鍵重點整理

問題 1 與 2 其實是同一條規則的兩面:Android 網路請求不能跑在主執行緒(否則拋 NetworkOnMainThreadException),而 UI 更新又只能在建立該 View 的執行緒上進行。兩者合起來就決定了必然是「子執行緒下載 + runOnUiThread 更新進度」的結構。

percent 的計算要特別小心:寫成 100 * sum / contentLength 會因為整數除法永遠得到 0,必須先轉成浮點數(100.0 * sum)再整體轉回 int。

至於暫停與繼續(問題 4),這個版本還沒有實作。要做真正的斷點續傳,需要把已下載的位元組寫入本機檔案,記錄下載位置,重新開始時帶上 Range 請求標頭從中斷處續傳。這部分留待後續補充。

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