ImageCache 源码分析_技巧获得

ImageCache

 public static ImageCache getInstance(
            FragmentManager fragmentManager, ImageCacheParams cacheParams) {
 
        // Search for, or create an instance of the non-UI RetainFragment
        final RetainFragment mRetainFragment = findOrCreateRetainFragment(fragmentManager);
 
        // See if we already have an ImageCache stored in RetainFragment
        ImageCache imageCache = (ImageCache) mRetainFragment.getObject();
 
        // No existing ImageCache, create one and store it in RetainFragment
        if (imageCache == null) {
            imageCache = new ImageCache(cacheParams);
            mRetainFragment.setObject(imageCache);
        }
 
        return imageCache;
    }
 /**
     * A simple non-UI Fragment that stores a single Object and is retained over configuration
     * changes. It will be used to retain the ImageCache object.
     */
    public static class RetainFragment extends Fragment {
        private Object mObject;
 
        /**
         * Empty constructor as per the Fragment documentation
         */
        public RetainFragment() {}
 
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
 
            // Make sure this Fragment is retained over a configuration change
            setRetainInstance(true);
        }
 
        /**
         * Store a single object in this Fragment.
         *
         * @param object The object to store
         */
        public void setObject(Object object) {
            mObject = object;
        }
 
        /**
         * Get the stored object.
         *
         * @return The stored object
         */
        public Object getObject() {
            return mObject;
        }
    }

发现在ImageCache单例中使用了一个 RetainFragment 并将单例ImageCache 放到其中,
这么做的原因:在使用和未使用Fragment的情况下,强制旋转屏幕,你会发现从保留内存缓存加载图片时几乎没有滞后。


参考资料

 

https://developer.android.com/samples/DisplayingBitmaps/src/com.example.android.displayingbitmaps/util/ImageCache.html#l105

http://www.trinea.cn/android/android-imagecache/

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。