我已经创建了一个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()方法的用途是什么?
发布于 2011-08-31 13:26:16
这一点类似于在C语言中清除指针的想法(如果你熟悉的话)。它用于使与a关联的数据为垃圾收集做好准备,以便在不需要时将内存/数据低效地绑定到a。阅读更多here。
重要的是要注意,这并不是真正必要的,除非你真的重用了"a“。如果该对象不再使用,GC会自动为您清除此数据。但是,TypedArray之所以不同,是因为TypedArray具有其他内部数据,必须将这些数据返回(称为StyledAttributes)到TypedArray以便稍后重用。阅读有关该here的信息。
发布于 2011-08-31 13:29:47
recycle()使分配的内存立即返回到可用池,并且在垃圾收集之前不会停留。此方法也适用于Bitmap。
发布于 2016-11-04 14:42:26
回收基本上是指..释放/清除与相应资源相关联的所有数据。在Android中,我们可以找到位图和TypedArray的循环使用。
如果你检查这两个源文件,你会发现一个布尔变量"mRecycled“,它是”false“(默认值)。当调用recycle时,它被赋值为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;
}
}TypedArray.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。
一旦TypedArray的"mRecycled“为真,那么在获取其属性时,它将抛出RuntimeException,声明”无法调用回收的实例!“
在Bitmap中也有类似的行为。希望能有所帮助。
https://stackoverflow.com/questions/7252839
复制相似问题