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

Android 非同步載入網路圖片引發記憶體溢出的解法

編輯:關於 Android 程式設計

在 ListView 或畫廊裡載入網路圖片,是新手最容易撞上 OutOfMemoryError 的地方。一張幾 MB 的原始圖片解成 Bitmap 可能要吃掉數十 MB 記憶體,而 App 的可用堆通常只有一二十 MB。本文示範以 AsyncTask 做非同步下載,並用 inSampleSize 做降採樣來避開溢出。測試環境為 Android 2.1 以上。

一、Manifest 權限

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

二、非同步圖片類 ImageDownloadTask

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.widget.ImageView;

public class ImageDownloadTask extends AsyncTask<Object, Object, Bitmap> {
    private ImageView imageView = null;

    /*
     * 這裡獲取到手機的解析度大小
     */
    public void setDisplayWidth(int width) {
        _displaywidth = width;
    }

    public int getDisplayWidth() {
        return _displaywidth;
    }

    public void setDisplayHeight(int height) {
        _displayheight = height;
    }

    public int getDisplayHeight() {
        return _displayheight;
    }

    public int getDisplayPixels() {
        return _displaypixels;
    }

    private int _displaywidth = 480;
    private int _displayheight = 800;
    private int _displaypixels = _displaywidth * _displayheight;

    @Override
    protected Bitmap doInBackground(Object... params) {
        Bitmap bmp = null;
        imageView = (ImageView) params[1];
        try {
            String url = (String) params[0];
            bmp = getBitmap(url, _displaypixels, true);
        } catch (Exception e) {
            return null;
        }
        return bmp;
    }

    protected void onPostExecute(Bitmap result) {
        if (imageView != null && result != null) {
            imageView.setImageBitmap(result);
            if (null != result && result.isRecycled() == false)
                System.gc();
        }
    }

    /**
     * 通過 URL 獲得網上圖片。如:https://www.xxxxxx.com/xx.jpg
     */
    public Bitmap getBitmap(String url, int displaypixels, Boolean isBig)
            throws MalformedURLException, IOException {
        Bitmap bmp = null;
        BitmapFactory.Options opts = new BitmapFactory.Options();
        InputStream stream = new URL(url).openStream();
        byte[] bytes = getBytes(stream);
        // 這 3 句是處理圖片溢出的 begin
        // (如果不需要處理溢出,直接 opts.inSampleSize = 1;)
        opts.inJustDecodeBounds = true;
        BitmapFactory.decodeByteArray(bytes, 0, bytes.length, opts);
        opts.inSampleSize = computeSampleSize(opts, -1, displaypixels);
        // end
        opts.inJustDecodeBounds = false;
        bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length, opts);
        return bmp;
    }

    /**
     * 數據流轉成 byte[] 數組
     */
    private byte[] getBytes(InputStream is) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] b = new byte[2048];
        int len = 0;
        try {
            while ((len = is.read(b, 0, 2048)) != -1) {
                baos.write(b, 0, len);
                baos.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        byte[] bytes = baos.toByteArray();
        return bytes;
    }

    /*
     * 處理圖片 bitmap size exceeds VM budget(Out Of Memory 記憶體溢出)
     */
    private int computeSampleSize(BitmapFactory.Options options,
            int minSideLength, int maxNumOfPixels) {
        int initialSize = computeInitialSampleSize(options, minSideLength, maxNumOfPixels);
        int roundedSize;
        if (initialSize <= 8) {
            roundedSize = 1;
            while (roundedSize < initialSize) {
                roundedSize <<= 1;
            }
        } else {
            roundedSize = (initialSize + 7) / 8 * 8;
        }
        return roundedSize;
    }

    private int computeInitialSampleSize(BitmapFactory.Options options,
            int minSideLength, int maxNumOfPixels) {
        double w = options.outWidth;
        double h = options.outHeight;
        int lowerBound = (maxNumOfPixels == -1) ? 1 : (int) Math.ceil(Math
                .sqrt(w * h / maxNumOfPixels));
        int upperBound = (minSideLength == -1) ? 128 : (int) Math.min(
                Math.floor(w / minSideLength), Math.floor(h / minSideLength));
        if (upperBound < lowerBound) {
            return lowerBound;
        }
        if ((maxNumOfPixels == -1) && (minSideLength == -1)) {
            return 1;
        } else if (minSideLength == -1) {
            return lowerBound;
        } else {
            return upperBound;
        }
    }
}

三、呼叫測試

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

    ImageDownloadTask imgtask = new ImageDownloadTask();

    /* 這裡是獲取手機螢幕的解析度,用來處理圖片溢出問題 begin */
    DisplayMetrics dm = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(dm);
    imgtask.setDisplayWidth(dm.widthPixels);
    imgtask.setDisplayHeight(dm.heightPixels);
    /* end */

    ImageView imageView_test = (ImageView) findViewById(R.id.imageView_test);
    imgtask.execute("https://pic.qukantu.com/big/7515/201201031116491.jpg", imageView_test);
}

四、原理小結

整個方案由兩半組成。

非同步:透過繼承 AsyncTask<Object, Object, Bitmap>,把網路請求放到 doInBackground 的背景執行緒,下載完成後在 onPostExecute 回到主執行緒設定 ImageView。少了這層包裝,在主執行緒做網路請求會直接收到 NetworkOnMainThreadException。

防溢出:核心技巧是 兩段式解碼。第一次呼叫 decodeByteArray 時把 inJustDecodeBounds 設為 true,這時候只讀取圖片的寬高,不真正配置像素記憶體;拿到尺寸後,用 computeSampleSize 算出合適的 inSampleSize;最後把 inJustDecodeBounds 設回 false 再解一次,這次才真的產生 Bitmap,而且已經是縮小過的版本。說穿了就是:依裝置解析度把圖片先降採樣再載入。

幾個可以更好的地方

第一,範例把整張圖片先讀進 byte 陣列再解碼,等於在記憶體裡多留了一份完整副本,其實可以直接把 InputStream 交給 decodeStream,省下一份暫存空間。

第二,System.gc() 不該手動呼叫。它只是「建議」虛擬機器進行垃圾回收,實際時機由 VM 決定,效果有限還會造成不必要的停頓。正確做法是讓 Bitmap 在不需要時自然被回收,並在 Activity 銷毀時呼叫 recycle()。

第三,computeSampleSize 這套邏輯在後續版本已被系統內建的 BitmapFactory.Options.inPreferredConfig 與 Glide、Picasso 等圖片庫完整封裝。新專案請直接採用這類成熟方案,它們還免費附帶記憶體/磁碟快取與請求取消機制,能避免列表滑動時圖片錯位的老問題。

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