即使我回收位图,内存使用也不会减少

Memory usage does not decrease even I recycle bitmaps

我有 A 和 B 活动。当我从 activity A 开始 activity B 时,我在 activity B 上设置静态位图变量。我在屏幕上显示该位图并旋转它。

当 activity B 完成时,我在 onDestroy() 方法上回收所有位图,但内存使用量没有减少。

@Override
protected void onDestroy() {
    super.onDestroy();
    if (bitmap90 != null) {
        bitmap90.recycle();
        bitmap90 = null;
    }
    if (bitmap180 != null) {
        bitmap180.recycle();
        bitmap180 = null;

    }
    if (bitmap270 != null) {
        bitmap270.recycle();
        bitmap270 = null;
    }

    if (mBitmap != null) {
        mBitmap.recycle();
        mBitmap = null;
    }

    if (((BitmapDrawable) ivOriginal.getDrawable()).getBitmap() != null) {
        ((BitmapDrawable) ivOriginal.getDrawable()).getBitmap().recycle();
        ivOriginal.setImageDrawable(null);
    }

    if (((BitmapDrawable) ivOriginal90.getDrawable()).getBitmap() != null) {
        ((BitmapDrawable) ivOriginal90.getDrawable()).getBitmap().recycle();
        ivOriginal90.setImageDrawable(null);
    }

    System.gc();
}

来自Android Developer

Free the native object associated with this bitmap, and clear the reference to the pixel data. This will not free the pixel data synchronously; it simply allows it to be garbage collected if there are no other references. The bitmap is marked as "dead", meaning it will throw an exception if getPixels() or setPixels() is called, and will draw nothing. This operation cannot be reversed, so it should only be called if you are sure there are no further uses for the bitmap. This is an advanced call, and normally need not be called, since the normal GC process will free up this memory when there are no more references to this bitmap.

recycle 只是确保每次调用 GC 时都会回收您的位图。 System.gc 也是如此,它不能确保 gc 现在会 运行,它只会要求 gc 运行 但 GC 只会在系统需要时 运行 运行.

所以放轻松,如果你正在回收位图,它们最终会被回收,只是给它一些时间。