第二次处理位图时OutOfMemoryError



我在一个活动中处理了许多位图来创建一个AnimationDrawable,它工作得很完美(尽管它使用了很多内存)。但是当用户按回并返回到MainActivity时,内存并没有被释放。

在那一刻:

  • 如果用户然后重新启动第二个活动来创建另一个活动AnimationDrawable,会发生OOMError,因为内存分配给我的应用程序不能同时包含两个AnimationDrawables时间。
  • 如果用户调用finish(),应用程序保持缓存,内存也不会释放。

如何释放内存?我尝试在第二个活动结束时将所有变量设置为null,我尝试在不同时刻调用system.gc()。

这部分代码应该足够了:

try {
        d = (BitmapDrawable) BitmapDrawable.createFromStream(new BufferedInputStream(new FileInputStream(src)), null);
        b = ((BitmapDrawable) d).getBitmap();
        b = Bitmap.createScaledBitmap(b, 300, 450, true);
        d = new BitmapDrawable(b);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
        animation.addFrame(d,1000/fps); // animation is an AnimationDrawable

这部分代码在for循环中,它通常被重复大约70到100次,动画因此相当"沉重"。我怎样才能摆脱它?我希望应用程序"忘记它"一旦第二个活动暂停。

非常感谢。:)

当您不再需要Bitmap对象时调用.recycle()方法:

http://developer.android.com/reference/android/graphics/Bitmap.html回收()

最新更新