Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android 讀取網路圖片並顯示下載進度條的完整實作

編輯:Android 開發實例

本節動手做一個小程式:從伺服器抓一張圖片下載到本機,過程中彈出讀取進度提示,下載完成後再把圖片顯示在畫面上。整個流程使用多執行緒處理網路 IO,並內建「本地快取優先」的判斷邏輯,第二次開啟同一張圖時不必再走網路。

功能拆解

  • 以 HttpURLConnection 連線並讀取圖片位元資料。
  • 透過 Handler 把 UI 更新送回主執行緒。
  • 以 ProgressDialog 呈現讀取中的等待狀態。
  • 把下載結果寫入應用程式快取目錄,並利用 If-Modified-Since 做 304 判定。

一、Activity 主體

點擊按鈕後另開一條執行緒抓取圖片,抓之前先跳進度框,抓完再關掉並設定 ImageView。所有涉及介面的操作都包在 handler.post() 裡,因為子執行緒不能直接改 UI。

package cn.itcast.pic;

import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class mainActivity extends Activity {

    private TextView addressET;
    private ImageView imageIV;
    private Handler handler = new Handler();   // 在主執行緒建立 Handler
    private ProgressDialog dialog;
    private ImageService service;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        addressET = (TextView) this.findViewById(R.id.addressET);
        imageIV = (ImageView) this.findViewById(R.id.imageIV);

        service = new ImageService(this);
    }

    public void onClick(View v) {
        // 網路下載放到新執行緒,避免阻塞主執行緒
        new Thread() {
            public void run() {
                try {
                    String address = addressET.getText().toString();

                    // 透過匿名 Runnable 把「顯示進度框」丟回主執行緒執行
                    handler.post(new Runnable() {
                        public void run() {
                            dialog = new ProgressDialog(mainActivity.this);
                            dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                            dialog.setMessage("請稍候...");
                            dialog.setCancelable(false);   // 不允許使用者取消
                            dialog.show();
                        }
                    });

                    // 耗時的網路讀取在新執行緒中進行
                    final Bitmap image = service.getImage(address);

                    handler.post(new Runnable() {
                        public void run() {
                            dialog.dismiss();
                            imageIV.setImageBitmap(image);   // 更新 UI 必須回到主執行緒
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                    Toast.makeText(getApplicationContext(), "服務器忙,請稍後再試!", 0).show();
                }
            }
        }.start();
    }
}

二、圖片下載服務 ImageService

這支類別負責真正的網路溝通與快取策略:

  1. 用 URL 物件封裝位址並開啟連線,設定讀取逾時。
  2. 檢查快取目錄裡有沒有同名檔案,有的話把最後修改時間帶進請求標頭。
  3. 依回應碼分流:200 表示要下載並寫入快取,304 表示直接讀本地檔。
  4. 寫快取另外開一條執行緒,讓畫面不必等磁碟 I/O。
package cn.itcast.pic;

import java.io.File;
import java.io.FileOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

import android.accounts.NetworkErrorException;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;

public class ImageService {

    private Context context;

    public ImageService(Context context) {
        super();
        this.context = context;
    }

    public Bitmap getImage(String address) throws Exception {
        // 1. 以 URL 物件封裝位址並建立連線
        URL url = new URL(address);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(3000);

        // 2. 判斷是否已有快取檔
        File cacheFile = new File(context.getCacheDir(),
                URLEncoder.encode(address));
        if (cacheFile.exists()) {
            // 帶入快取檔最後修改時間,讓伺服器決定是否回 304
            conn.setIfModifiedSince(cacheFile.lastModified());
        }

        // 3. 依狀態碼決定後續動作
        int code = conn.getResponseCode();
        if (code == 200) {
            byte[] data = Util.read(conn.getInputStream());
            Bitmap bm = BitmapFactory.decodeByteArray(data, 0, data.length);
            weiteCache(cacheFile, bm);
            return bm;
        } else if (code == 304) {
            // 圖片沒有變動,直接讀本地快取
            return BitmapFactory.decodeFile(cacheFile.getAbsolutePath());
        }

        // 其他狀態碼一律視為錯誤
        throw new NetworkErrorException("訪問服務器出錯:" + code);
    }

    // 4. 另開執行緒寫入快取,避免拖累畫面顯示
    private void weiteCache(final File cacheFile, final Bitmap bm) {
        new Thread() {
            public void run() {
                try {
                    FileOutputStream fos = new FileOutputStream(cacheFile);
                    bm.compress(CompressFormat.JPEG, 100, fos);
                    fos.close();
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }.start();
    }
}

三、串流讀取工具類別 Util

把 InputStream 逐段讀進 ByteArrayOutputStream,最後一次轉成位元組陣列,交給 BitmapFactory 解碼。

package cn.itcast.pic;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class Util {

    public static byte[] read(InputStream in) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len;
        while ((len = in.read(buffer)) != -1) {
            baos.write(buffer, 0, len);
        }
        baos.close();
        return baos.toByteArray();
    }
}

四、主介面配置檔

上方一列是輸入位址的 EditText 與觸發下載的按鈕,下方 ImageView 用來呈現結果。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" >

        <EditText
            android:id="@+id/addressET"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:inputType="textEmailAddress" >
            <requestFocus />
        </EditText>

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="onClick"
            android:text=" GO " />
    </LinearLayout>

    <ImageView
        android:id="@+id/imageIV"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

別忘了的兩件小事

一是要在 AndroidManifest.xml 加上 android.permission.INTERNET 權限,否則連線會直接失敗;二是快取檔案建議後續加上大小上限與過期清理,避免長期使用佔滿應用程式可用的儲存空間。

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