4

重複の可能性:
Android:画像をビットマップオブジェクトにロードする際のメモリ不足の問題

私はアンドロイドの分野で新しいです。Androidでメモリ消費を減らす方法がわかりません。私のアプリケーションでは、多数の画像がWebから描画され、グリッドビューに表示されます。アプリケーションを実行すると、「メモリ不足の問題が発生します」。

私を助けてください

4

1 に答える 1

3

1)画像を縮小してサイズを小さくする

/**
 * decodes image and scales it to reduce memory consumption
 * 
 * @param file
 * @param requiredSize
 * @return
 */
public static Bitmap decodeFile(File file, int requiredSize) {
    try {

        // Decode image size
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;
        BitmapFactory.decodeStream(new FileInputStream(file), null, o);

        // The new size we want to scale to

        // Find the correct scale value. It should be the power of 2.
        int width_tmp = o.outWidth, height_tmp = o.outHeight;
        int scale = 1;
        while (true) {
            if (width_tmp / 2 < requiredSize
                    || height_tmp / 2 < requiredSize)
                break;
            width_tmp /= 2;
            height_tmp /= 2;
            scale *= 2;
        }

        // Decode with inSampleSize
        BitmapFactory.Options o2 = new BitmapFactory.Options();
        o2.inSampleSize = scale;

        Bitmap bmp = BitmapFactory.decodeStream(new FileInputStream(file),
                null, o2);

        return bmp;

    } catch (FileNotFoundException e) {
    } finally {
    }
    return null;
}

2)使用bitmap.Recycle();

3)System.gc();ガベージ コレクタを実行するのに適した時期であることを VM に示すために使用します。

于 2013-02-02T12:36:49.310 に答える