This answer告诉我,调用TypedArray的recycle()方法允许对其进行垃圾回收。我的问题是,为什么TypedArray特别需要一个方法来对其进行垃圾回收?为什么它不能像普通对象一样等待垃圾回收呢?
发布于 2012-12-11 01:06:35
这是缓存purporse所必需的。当您调用recycle时,这意味着这个对象可以从此重用。在内部,TypedArray包含的数组很少,所以为了不在每次使用TypedArray时都分配内存,它被作为静态字段缓存在Resources类中。您可以查看TypedArray.recycle()方法代码:
/**
* Give back a previously retrieved StyledAttributes, for later re-use.
*/
public void recycle() {
synchronized (mResources.mTmpValue) {
TypedArray cached = mResources.mCachedStyledAttributes;
if (cached == null || cached.mData.length < mData.length) {
mXml = null;
mResources.mCachedStyledAttributes = this;
}
}
}因此,当您调用recycle时,您的TypedArray对象只是返回到缓存。
发布于 2015-07-15 03:32:04
@Andrei Mankevich我刚刚检查了最新版本的Android SDK,似乎对recycle()做了一些更改。请检查以下代码:
/**
* Recycle the TypedArray, to be re-used by a later caller. After calling
* this function you must not ever touch the typed array again.
*/
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;
mResources.mTypedArrayPool.release(this);
}https://stackoverflow.com/questions/13805502
复制相似问题