测试TypedArray recycle()不会抛出RuntimeException

时间:2017-09-28 11:41:20

标签: android exception android-resources android-styles typedarray

我使用此代码测试了TypedArray recycle,期望根据文档获得运行时异常,但我没有得到。

  

循环

     

在API级别1中添加   void recycle()重新使用TypedArray   被后来的呼叫者重用。调用此功能后,您不能   再次触摸打字阵列。

     

如果TypedArray已被回收,则抛出RuntimeException。

    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()次调用,而在变量窗格a中未进行null

我进行此测试的原因是因为我不能100%确定是否可以在a.recycle()创建a的范围内调用 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

仍然没有$('#details-1').modal('show')

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

1 个答案:

答案 0 :(得分:1)

Here's API {的实施TypedArray#recycle()

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

显然,docs说明了最新API的实现,并且您正在使用API​​ 15运行您的应用程序。

相关问题