在TypedArray中使用recycle()方法有什么用处

问题描述 投票:36回答:4

我创建了一个GalleryViewImageView,当在图库中单击某个项目时,它会显示更大的图像。我使用下面的代码来实现ImageAdapter

public ImageAdapter(Context c)
{
    context = c;
    TypedArray a = obtainStyledAttributes(R.styleable.gallery1);
    itemBackground = a.getResourceId(R.styleable.gallery1_android_galleryItemBackground, 0);    
    a.recycle();    
}

当我删除语句a.recycle()没有变化,应用程序像以前一样正常运行,但我读到的任何地方都必须回收typedArray。当我的应用程序运行方式没有变化时,recycle()方法的用途是什么?

android
4个回答
34
投票

这一点类似于用C语言清除指针的想法(如果你熟悉它)。它用于使与a相关的数据准备好进行垃圾收集,因此当不需要时,内存/数据不会低效地绑定到a。阅读更多here

重要的是要注意,除非你真的重用“a”,否则这不是必需的。如果不再使用该对象,GC应自动清除此数据。然而,TypedArray不同的原因是因为TypedArray有其他内部数据必须返回(称为StyledAttributes)到TypedArray以供以后重用。了解那个here


6
投票

recycle()使分配的内存立即返回到可用池,并且在垃圾收集之前不会保留。这种方法也适用于Bitmap


0
投票

回收基本上意味着...免费/清除与相应资源相关的所有数据。在Android中,我们可以找到Bitmap和TypedArray的回收。

如果你检查两个源文件,那么你可以找到一个布尔变量“mRecycled”,它是“false”(默认值)。调用回收时,它被指定为“true”。

所以,现在如果你检查那个方法(两个类中的循环方法),那么我们可以观察到它们正在清除所有的值。

这里参考方法。

bitmap.Java:

    public void recycle() {
    if (!mRecycled && mNativePtr != 0) {
        if (nativeRecycle(mNativePtr)) {
            // return value indicates whether native pixel object was actually recycled.
            // false indicates that it is still in use at the native level and these
            // objects should not be collected now. They will be collected later when the
            // Bitmap itself is collected.
            mBuffer = null;
            mNinePatchChunk = null;
        }
        mRecycled = true;
    }
}

type的array.Java

    public void recycle() {
    if (mRecycled) {
        throw new RuntimeException(toString() + " recycled twice!");
    }

    mRecycled = true;

    // These may have been set by the client.
    mXml = null;
    mTheme = null;
    mAssets = null;

    mResources.mTypedArrayPool.release(this);
}

这条线

mResources.mTypedArrayPool.release(this);

将从默认值为5的SunchronisedPool中释放typedArray。因此,在清除它时不应再使用相同的typedArray。

一旦“mdcycled”的TypedArray为真,那么在获取其属性时,它将抛出RuntimeException,说“无法调用循环实例!”。

在Bitmap的情况下也有类似的行为。希望能帮助到你。


0
投票

由于它的使用已经结束[after initializing our local attributes]所以我们将它回收到资源池

简单

© www.soinside.com 2019 - 2024. All rights reserved.