0

在阅读了很多相关帖子之后,我还没有找到解决这个问题的有效方法。当我的应用程序使用静态方法调整 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异常。

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

4

1 回答 1

0

在返回之前执行此操作:

img.recycle();
img = null;
于 2013-05-28T17:02:34.873 回答