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

Android 從網路下載圖片:最小實作與該補上的三件事

編輯:關於 Android 開發

Android 從網路下載圖片:最小實作與該補上的三件事

「把一個圖片 URL 變成 Bitmap」是每個 Android 開發者都寫過的需求。最小可用的版本只需要 URL、串流與解碼三個步驟:

package cn.com.hh.http;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

public class Download {

    /**
     * 從網路下載圖片資源
     *
     * @param imgPath 圖片網址
     * @return 解碼後的 Bitmap,失敗時為 null
     */
    public Bitmap DownloadImg(String imgPath) {
        Bitmap bmp = null;
        try {
            URL imgUrl = new URL(imgPath);
            URLConnection con = imgUrl.openConnection();
            InputStream in = con.getInputStream();
            bmp = BitmapFactory.decodeStream(in);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bmp;
    }
}

程式邏輯很直白:開連線、拿輸入串流、交給 BitmapFactory 解碼。但這段程式碼若直接搬進 App,馬上會遇到三個問題,值得逐一補上。

一、不能在主執行緒做網路連線

從 Android 3.0(Honeycomb)開始,NetworkOnMainThreadException 會直接讓這種寫法崩潰。下載必須離開 UI 執行緒,再把結果丟回主執行緒更新畫面。現代專案通常交給協程或 ExecutorService 處理:

public void loadImageAsync(Context context, String url, ImageView target) {
    ExecutorService pool = Executors.newSingleThreadExecutor();
    Handler main = new Handler(Looper.getMainLooper());
    pool.execute(() -> {
        final Bitmap bmp = downloadImg(url);
        main.post(() -> {
            if (bmp != null) {
                target.setImageBitmap(bmp);
            }
        });
    });
}

二、記得宣告權限,也記得關掉串流

網路存取屬於受限資源,Manifest 中必須先聲明:

<uses-permission android:name="android.permission.INTERNET" />

另外,InputStream 與 HttpURLConnection 都持有系統資源,應以 try-with-resources 確保釋放,並明確設定逾時,避免連線卡死:

public Bitmap downloadImg(String imgPath) {
    HttpURLConnection conn = null;
    try (InputStream in = new URL(imgPath).openStream()) {
        return BitmapFactory.decodeStream(in);
    } catch (IOException e) {
        Log.e("Download", "下載失敗:" + imgPath, e);
        return null;
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
}

三、大圖會直接 OOM

decodeStream 會把整張圖完整載入記憶體,一張幾 MB 的照片就足以讓低階裝置當機。實務上應改用 BitmapFactory.Options 的 inJustDecodeBounds 先讀尺寸,再依目標檢視大小決定 inSampleSize 做降採樣:

BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inJustDecodeBounds = true;
BitmapFactory.decodeStream(in, null, opts);

int sample = 1;
while (opts.outWidth / (sample * 2) >= targetWidth) {
    sample *= 2;
}
opts.inSampleSize = sample;
opts.inJustDecodeBounds = false;
return BitmapFactory.decodeStream(new URL(imgPath).openStream(), null, opts);

後記

如果只是想顯示網路圖片,其實不必自己造輪子——Glide、Coil 這類函式庫已經把執行緒調度、記憶體與磁碟快取、生命週期綁定、降採樣都做完了,還能自動取消不再需要的請求。上面這段程式碼的價值,在於理解「一個圖片請求背後到底發生了什麼」,這樣在函式庫行為不如預期時,你才知道該往哪裡查。

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