萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> Android 開發

Android 非同步下載網路資源完整方案:圖片與文字的異步獲取、快取與顯示

網路資源(圖片、JSON、HTML)的下載與顯示是 App 開發的高頻需求。本文提供一套完整、可生產環境使用的方案:封裝 HTTP 連線取得 InputStream、分別實作圖片/文字下載方法、採用 AsyncTask 執行非同步任務並支援進度回呼與 UI 更新,代碼結構清晰,易於擴充為通用網路層基礎。

架構分層

  1. 底層連線封裝: openHttpConnection(String url) → 回傳 InputStream,統一處理 HTTP 協議、重導向、錯誤碼判斷。
  2. 資源解析層: downloadImage() 解碼為 Bitmap;downloadText() 讀取字串內容。
  3. 非同步任務層: DownloadImageTask extends AsyncTask,支援多圖批次下載、進度條更新、完成通知。

核心程式碼實作

1. 統一 HTTP 連線方法

private InputStream openHttpConnection(String urlString) throws IOException {
    InputStream in = null;
    int response = -1;
    URL url = new URL(urlString);
    URLConnection conn = url.openConnection();

    if (!(conn instanceof HttpURLConnection)) {
        throw new IOException("It is not an HTTP connection");
    }

    try {
        HttpURLConnection httpConn = (HttpURLConnection) conn;
        httpConn.setAllowUserInteraction(false);
        httpConn.setInstanceFollowRedirects(true);
        httpConn.setRequestMethod("GET");
        httpConn.connect();

        response = httpConn.getResponseCode();
        if (response == HttpURLConnection.HTTP_OK) {
            in = httpConn.getInputStream();
        }
    } catch (Exception ex) {
        Log.e("Networking", ex.getLocalizedMessage());
        throw new IOException("Error connecting");
    }
    return in;
}

2. 圖片與文字下載解析

// 下載圖片 → Bitmap
private Bitmap downloadImage(String url) {
    Bitmap bitmap = null;
    InputStream in = null;
    try {
        in = openHttpConnection(url);
        bitmap = BitmapFactory.decodeStream(in);
        if (in != null) in.close();
    } catch (IOException e) {
        Log.e("NetworkingActivity", e.getLocalizedMessage());
    }
    return bitmap;
}

// 下載文字 → String
private String downloadText(String url) {
    final int BUFFER_SIZE = 2000;
    InputStream is = null;
    try {
        is = openHttpConnection(url);
    } catch (IOException e) {
        e.printStackTrace();
        return "";
    }
    InputStreamReader isr = new InputStreamReader(is);
    char[] inputBuffer = new char[BUFFER_SIZE];
    StringBuilder str = new StringBuilder();
    try {
        int charRead;
        while ((charRead = isr.read(inputBuffer)) > 0) {
            str.append(inputBuffer, 0, charRead);
        }
        is.close();
    } catch (IOException e) {
        e.printStackTrace();
        return "";
    }
    return str.toString();
}

3. 非同步下載圖片任務(支援進度回呼)

private class DownloadImageTask extends AsyncTask {
    private long imagesCount = 0;
    private ProgressBar progressBar;

    public DownloadImageTask(ProgressBar pBar) {
        this.progressBar = pBar;
    }

    @Override
    protected Long doInBackground(String... urls) {
        for (int i = 0; i < urls.length; i++) {
            Bitmap imageDownloaded = downloadImage(urls[i]);
            if (imageDownloaded != null) {
                imagesCount++;
                publishProgress(imageDownloaded); // 觸發 onProgressUpdate
                try { Thread.sleep(300); } catch (InterruptedException e) { e.printStackTrace(); }
            }
        }
        return imagesCount;
    }

    @Override
    protected void onProgressUpdate(Bitmap... bitmaps) {
        // 顯示最新下載的圖片
        ivImg.setImageBitmap(bitmaps[0]);
        // 更新進度條(假設最多 10 張)
        progressBar.setProgress((int) (imagesCount * 10));
    }

    @Override
    protected void onPostExecute(Long imageDownloaded) {
        String msg = "下載完成!共下載 " + imagesCount + " 張圖片";
        Toast.makeText(getBaseContext(), msg, Toast.LENGTH_LONG).show();
    }
}

4. 啟動任務

String[] imageUrls = {
    "https://example.com/img1.jpg",
    "https://example.com/img2.jpg"
    // ...
};
new DownloadImageTask(progressBar).execute(imageUrls);

生產環境優化建議

  • 替換 AsyncTask: Android 11 (API 30) 起 AsyncTask 標記棄用,建議遷移至 Kotlin Coroutines + Retrofit/OkHttp 或 RxJava。
  • 加入記憶體/磁碟快取: 整合 Glide、Picasso、Coil 等成熟圖片載入庫,自動處理快取、生命週期、佔位圖、錯誤重試。
  • 錯誤重試與超時: 設定 HttpURLConnection.setConnectTimeout()、setReadTimeout(),並實作指數退避重試機制。
  • 生命週期感知: 在 onDestroy() 取消任務(task.cancel(true)),避免 Activity 銷毀後更新 UI 導致洩漏。

總結

本文示範從零構建網路下載棧的核心邏輯,適合理解底層原理或輕量級專案無法引入大型庫時使用。實際專案中,強烈建議直接採用成熟網路框架(OkHttp + Retrofit + Coroutines),專注於業務邏輯而非重複造輪子。

copyright © 萬盛學電腦網 all rights reserved