我创建了一个GalleryView
和ImageView
,当在图库中单击某个项目时,它会显示更大的图像。我使用下面的代码来实现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()
方法的用途是什么?
recycle()
使分配的内存立即返回到可用池,并且在垃圾收集之前不会保留。这种方法也适用于Bitmap
。
回收基本上意味着...免费/清除与相应资源相关的所有数据。在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的情况下也有类似的行为。希望能帮助到你。
由于它的使用已经结束[after initializing our local attributes
]所以我们将它回收到资源池
简单