避免在不使用静态图像时发生Android内存泄漏

4

我知道这个问题可能已经被解决了,但是我的Android应用程序存在内存泄漏的问题。我让它在用户库中循环显示不同的图片,每次用户按下按钮时就会切换一张图片。前几次运行正常,然后出现了内存溢出异常。我查了一下,似乎是即使图片没有被引用,它们仍然存储在堆上(?)。有办法可以强制清理内存,避免出现错误吗?我尝试过以下方法....

private void setImage() throws RemoteException{
    view.setBackgroundDrawable(null);
    currentBackground = Drawable.createFromPath(backgroundImageService.getCurrentImageLocation());
    view.setBackgroundDrawable(currentBackground);
}

更新:更新成功!!!

private void setImage() throws RemoteException{
    if(currentBackground != null){
        currentBackground.recycle();
    }
    currentBackground = BitmapFactory.decodeFile(backgroundImageService.getCurrentImageLocation());
    view.setBackgroundDrawable(new BitmapDrawable(currentBackground));
}

谢谢

1个回答

4
您可以使用 Bitmap.recycle() 方法,如果您能用 Bitmap 替换 Drawable 的话。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接