Android:使用Bitmap.createBitmap后泄漏内存

时间:2013-05-28 15:57:00

标签: android android-memory

经过多次阅读相关帖子后,我还没有找到解决这个问题的方法。 当我的应用程序调整Bitmap对象的大小时,使用静态方法:Bitmap.createBitmap,我认为它会泄漏内存。

我怀疑内存泄漏的方法:

HashMap < Integer , BoardImage > boardsImages = new HashMap<Integer, BoardImage>();

public synchronized void addBoard(BoardImage b) {

    // check if the board isn't already exists
    if (boardsImages.get( b.getBoardNumber() ) == null){ 
        parent.addButton(b.getBoardNumber()); // add new button
        numOfButtons++;
    }

    // resize the image to strech over the canves
    int newWidth = getWidth(), // the new width of the image
        newHeight = getHeight(),// the new height of the image
        width = b.getBoardBitmap().getWidth(),// the old width of the image
        height = b.getBoardBitmap().getHeight();// the old height of the image

    // resize the image
    Bitmap resized = resizeBitmap(newWidth, newHeight,width,height,b.getBoardBitmap());
    // update the object
    b.recycleBitmap();
    b.setBoardBitmap(resized);

    boardsImages.put(b.getBoardNumber(), b);
}

public Bitmap resizeBitmap(int newWidth, int newHeight,int curWidth,int curHeight,Bitmap img){

    float scaleWidth = ((float) newWidth) / curWidth;
    float scaleHeight = ((float) newHeight) / curHeight;

    Matrix matrix = new Matrix();
    matrix.postScale(scaleWidth, scaleHeight);

    Bitmap resized = Bitmap.createBitmap(img, 0, 0, curWidth, curHeight, matrix, true);

    return resized;
}

BoardImage类(部分内容):

transient private Bitmap boardBitmap = null;
public void setBoardBitmap(Bitmap b){       
    boardBitmap = b;
}

public Bitmap getBoardBitmap(){
    return boardBitmap;
}

public void recycleBitmap(){
    boardBitmap.recycle();
    boardBitmap = null;
}

使用调试器,在调用Bitmap.createBitmap的行之后,我在Logcat上收到此消息: Grow heap (frag case) to 8.169MB for 1818612-byte allocation

当堆大小达到其限制(在我的AVD中设置为32MB)时,程序崩溃并出现OutOfMemory异常。

如果需要更多代码,请告诉我,谢谢!

1 个答案:

答案 0 :(得分:0)

在返回之前这样做:

img.recycle();
img = null;