我已经创建了一个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
发布于 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
复制相似问题