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

Android 開發:實作檔案下載與進度條

編輯:關於 Android 開發

本文示範如何以 URLConnection 從網路下載檔案並寫入 SD 卡,同時透過 Handler 與 Message 機制回報下載進度,實作一個具備進度條的檔案下載功能。

一、下載檔案的核心程式碼

public void downFile(String url, String path, String fileName) throws IOException {
    if (fileName == null || fileName == "")
        this.FileName = url.substring(url.lastIndexOf("/") + 1);
    else
        this.FileName = fileName; // 若輸入新檔名則使用新檔名

    URL Url = new URL(url);
    URLConnection conn = Url.openConnection();
    conn.connect();
    InputStream is = conn.getInputStream();
    this.fileSize = conn.getContentLength(); // 依回應取得檔案大小
    if (this.fileSize <= 0) { // 內容長度為 0
        throw new RuntimeException("無法得知檔案大小 ");
    }
    if (is == null) { // 沒有下載串流
        sendMsg(Down_ERROR);
        throw new RuntimeException("無法取得檔案");
    }
    FileOutputStream FOS = new FileOutputStream(path + this.FileName);
    byte buf[] = new byte[1024];
    downLoadFilePosition = 0;
    int numread;
    while ((numread = is.read(buf)) != -1) {
        FOS.write(buf, 0, numread);
        downLoadFilePosition += numread;
    }
    try {
        is.close();
    } catch (Exception ex) { ; }
}

使用網路時,記得要在 AndroidManifest.xml 中加入網路存取權限。

二、以 Handler 更新進度條

若要顯示下載進度,可透過訊息傳遞機制,隨下載進度更新進度條:

private Handler downloadHandler = new Handler() { // 接收並處理進度訊息
    @Override
    public void handleMessage(Message msg) {
        if (!Thread.currentThread().isInterrupted()) {
            switch (msg.what) {
                case DOWN_START:
                    pb.setMax(fileSize); // 設定進度最大值
                case DOWN_POSITION:
                    pb.setProgress(downLoadFilePosition); // 設定目前進度
                    break;
                case DOWN_COMPLETE:
                    Toast.makeText(DownLoadFileTest.this, "下載完成!", 1).show();
                    break;
                case Down_ERROR:
                    String error = msg.getData().getString("下載出錯!");
                    Toast.makeText(DownLoadFileTest.this, error, 1).show();
                    break;
            }
        }
        super.handleMessage(msg);
    }
};

透過下載過程中持續發送位置訊息,即可讓進度條即時反映下載狀態;下載完成或出錯時也能給予使用者明確提示。

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