测试 TypedArray recycle() 不会抛出 RuntimeException

Testing TypedArray recycle() does not throw RuntimeException

我用这段代码测试了TypedArray recycle,希望根据文档得到运行时异常,但我没有得到。

recycle

added in API level 1
void recycle () Recycles the TypedArray, to be re-used by a later caller. After calling this function you must not ever touch the typed array again.

Throws RuntimeException if the TypedArray has already been recycled.

    public TimePickerPreference(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.TimePickerPreference, 0, 0);
        initTimePickerPreference(a);
        a.recycle();
    }
    protected void initTimePickerPreference(TypedArray a) {

        if (a != null)
            try {
                setTitle(a.getString(R.styleable.TimePickerPreference_android_title));
                mSummary = a.getString(R.styleable.TimePickerPreference_android_summary);
                mDefaultValue = a.getString(R.styleable.TimePickerPreference_android_defaultValue);
            } finally {
                a.recycle();
            }

    ...
    }

我使用 Android Studio 调试器跟踪代码,它经历了两次 a.recycle() 调用,而在 variables 窗格中 a 是未制作 null

我进行此测试的原因是因为我不能 100% 确定在与创建 a 的范围不同的范围内调用 a.recycle() 是否可以。

我更进一步重复了回收调用

    public TimePickerPreference(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.TimePickerPreference, 0, 0);
        initTimePickerPreference(a);
        a.recycle();
        a.recycle();
    }
    protected void initTimePickerPreference(TypedArray a) {

        if (a != null)
            try {
                setTitle(a.getString(R.styleable.TimePickerPreference_android_title));
                mSummary = a.getString(R.styleable.TimePickerPreference_android_summary);
                mDefaultValue = a.getString(R.styleable.TimePickerPreference_android_defaultValue);
            } finally {
                a.recycle();
                a.recycle();
            }

    ...
    }

还是没有RunTimeException.

这是一个错误吗?
我 运行 它在具有 Android IceCreamSandwich 版本 (API 15) 的 AVD 模拟设备上使用。

Here's 实施 TypedArray#recycle() 为 API 15:

 public void recycle() {
     synchronized (mResources.mTmpValue) {
         TypedArray cached = mResources.mCachedStyledAttributes;
         if (cached == null || cached.mData.length < mData.length) {
             mXml = null;
             mResources.mCachedStyledAttributes = this;
         }
     }
 }

Here's API 25 的实现:

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);
}

显然,文档说明了最新 API 的实施,而您 运行 您的应用 API 15.