Android Open Source - cube-sdk Cache Manager






From Project

Back to project page cube-sdk.

License

The source code is released under:

Apache License

If you think the Android project cube-sdk listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

package in.srain.cube.cache;
//ww w  .j av  a2 s. c o m
import android.content.Context;
import android.support.v4.util.LruCache;
import android.text.TextUtils;
import in.srain.cube.concurrent.SimpleExecutor;
import in.srain.cube.concurrent.SimpleTask;
import in.srain.cube.file.FileUtil;
import in.srain.cube.file.LruFileCache;
import in.srain.cube.request.JsonData;
import in.srain.cube.util.CLog;
import in.srain.cube.util.Debug;

/**
 * @author http://www.liaohuqiu.net
 */
public class CacheManager {

    private static final boolean DEBUG = Debug.DEBUG_CACHE;
    private static final String LOG_TAG = "cube_cache";

    private LruCache<String, CacheInfo> mMemoryCache;
    private LruFileCache mFileCache;

    private static final byte AFTER_READ_FROM_FILE = 0x01;
    private static final byte AFTER_READ_FROM_ASSERT = 0x02;
    private static final byte AFTER_CONVERT = 0x04;

    private static final byte DO_READ_FROM_FILE = 0x01;
    private static final byte DO_READ_FROM_ASSERT = 0x02;
    private static final byte DO_CONVERT = 0x04;

    private static final byte CONVERT_FOR_MEMORY = 0x03;
    private static final byte CONVERT_FOR_FILE = 0x01;
    private static final byte CONVERT_FOR_ASSERT = 0x02;
    private static final byte CONVERT_FOR_CREATE = 0x04;

    private Context mContext;

    public CacheManager(Context content, String cacheDir, int memoryCacheSizeInKB, int fileCacheSizeInKB) {
        mContext = content;

        mMemoryCache = new LruCache<String, CacheInfo>(memoryCacheSizeInKB * 1024) {
            @Override
            protected int sizeOf(String key, CacheInfo value) {
                return (value.getSize() + key.getBytes().length);
            }
        };
        mFileCache = new LruFileCache(content, cacheDir, fileCacheSizeInKB * 1024);
        mFileCache.initDiskCacheAsync();
        if (DEBUG) {
            CLog.d(LOG_TAG, "init file cache. dir: %s => %s, size: %s, used: %s", cacheDir, mFileCache.getCachePath(), mFileCache.getMaxSize(), mFileCache.getUsedSpace());
        }
    }

    public <T> void requestCache(ICacheAble<T> cacheAble) {
        InnerCacheTask<T> task = new InnerCacheTask<T>(cacheAble);
        task.beginQuery();
    }

    public <T> void continueAfterCreateData(ICacheAble<T> cacheAble, final String data) {
        setCacheData(cacheAble.getCacheKey(), data);
        InnerCacheTask<T> task = new InnerCacheTask<T>(cacheAble);
        task.beginConvertDataAsync(CONVERT_FOR_CREATE);
    }

    public void setCacheData(final String cacheKey, final String data) {
        if (TextUtils.isEmpty(cacheKey) || TextUtils.isEmpty(data)) {
            return;
        }
        if (DEBUG) {
            CLog.d(LOG_TAG, "%s, setCacheData", cacheKey);
        }
        SimpleExecutor.getInstance().execute(

                new Runnable() {
                    @Override
                    public void run() {
                        CacheInfo cacheInfo = CacheInfo.createForNow(data);
                        putDataToMemoryCache(cacheKey, cacheInfo);
                        mFileCache.write(cacheKey, cacheInfo.getCacheData());
                        mFileCache.flushDiskCacheAsyncWithDelay(1000);
                    }
                }
        );
    }

    private class InnerCacheTask<T1> extends SimpleTask {

        private ICacheAble<T1> mCacheAble;

        private CacheInfo mRawData;
        private T1 mResult;
        private byte mWorkType = 0;
        private byte mConvertFor = 0;
        private byte mCurrentStatus = 0;

        public InnerCacheTask(ICacheAble<T1> cacheAble) {
            mCacheAble = cacheAble;
        }

        void beginQuery() {

            if (mCacheAble.cacheIsDisabled()) {
                if (DEBUG) {
                    CLog.d(LOG_TAG, "%s, Cache is disabled, query from server", mCacheAble.getCacheKey());
                }
                mCacheAble.createDataForCache(CacheManager.this);
                return;
            }

            String cacheKey = mCacheAble.getCacheKey();

            // try to find in runtime cache
            mRawData = mMemoryCache.get(cacheKey);
            if (mRawData != null) {
                if (DEBUG) {
                    CLog.d(LOG_TAG, "%s, exist in list", mCacheAble.getCacheKey());
                }
                beginConvertDataAsync(CONVERT_FOR_MEMORY);
                return;
            }

            // try read from cache data
            boolean hasFileCache = mFileCache.has(mCacheAble.getCacheKey());
            if (hasFileCache) {
                beginQueryFromCacheFileAsync();
                return;
            }

            // try to read from assert cache file
            String assertInitDataPath = mCacheAble.getAssertInitDataPath();
            if (assertInitDataPath != null && assertInitDataPath.length() > 0) {
                beginQueryFromAssertCacheFileAsync();
                return;
            }

            if (DEBUG) {
                CLog.d(LOG_TAG, "%s, cache file not exist", mCacheAble.getCacheKey());
            }
            mCacheAble.createDataForCache(CacheManager.this);
        }

        @Override
        public void doInBackground() {
            if (DEBUG) {
                CLog.d(LOG_TAG, "%s, doInBackground: mWorkType: %s", mCacheAble.getCacheKey(), mWorkType);
            }
            switch (mWorkType) {

                case DO_READ_FROM_FILE:
                    doQueryFromCacheFileInBackground();
                    setCurrentStatus(AFTER_READ_FROM_FILE);
                    break;

                case DO_READ_FROM_ASSERT:
                    doQueryFromAssertCacheFileInBackground();
                    setCurrentStatus(AFTER_READ_FROM_ASSERT);
                    break;

                case DO_CONVERT:
                    doConvertDataInBackground();
                    setCurrentStatus(AFTER_CONVERT);
                    break;

                default:
                    break;
            }
        }

        @Override
        public void onFinish() {
            switch (mCurrentStatus) {
                case AFTER_READ_FROM_FILE:
                    beginConvertDataAsync(CONVERT_FOR_FILE);
                    break;
                case AFTER_READ_FROM_ASSERT:
                    beginConvertDataAsync(CONVERT_FOR_ASSERT);
                    break;

                case AFTER_CONVERT:
                    done();
                    break;

                default:
                    break;
            }
        }

        private void beginQueryFromCacheFileAsync() {
            if (DEBUG) {
                CLog.d(LOG_TAG, "%s, beginQueryFromCacheFileAsync", mCacheAble.getCacheKey());
            }
            mWorkType = DO_READ_FROM_FILE;
            restart();
            SimpleExecutor.getInstance().execute(this);
        }

        private void beginQueryFromAssertCacheFileAsync() {
            if (DEBUG) {
                CLog.d(LOG_TAG, "%s, beginQueryFromAssertCacheFileAsync", mCacheAble.getCacheKey());
            }
            mWorkType = DO_READ_FROM_ASSERT;
            restart();
            SimpleExecutor.getInstance().execute(this);
        }

        private void beginConvertDataAsync(byte convertFor) {
            if (DEBUG) {
                CLog.d(LOG_TAG, "%s, beginConvertDataAsync", mCacheAble.getCacheKey());
            }
            mConvertFor = convertFor;
            mWorkType = DO_CONVERT;
            restart();
            SimpleExecutor.getInstance().execute(this);
        }

        private void doQueryFromCacheFileInBackground() {
            if (DEBUG) {
                CLog.d(LOG_TAG, "%s, try read cache data from file", mCacheAble.getCacheKey());
            }

            String cacheContent = mFileCache.read(mCacheAble.getCacheKey());
            JsonData jsonData = JsonData.create(cacheContent);
            mRawData = CacheInfo.createFromJson(jsonData);
        }

        private void doQueryFromAssertCacheFileInBackground() {

            if (DEBUG) {
                CLog.d(LOG_TAG, "%s, try read cache data from assert file", mCacheAble.getCacheKey());
            }

            String cacheContent = FileUtil.readAssert(mContext, mCacheAble.getAssertInitDataPath());
            mRawData = CacheInfo.createInvalidated(cacheContent);
            putDataToMemoryCache(mCacheAble.getCacheKey(), mRawData);
        }

        private void doConvertDataInBackground() {
            if (DEBUG) {
                CLog.d(LOG_TAG, "%s, doConvertDataInBackground", mCacheAble.getCacheKey());
            }
            JsonData data = JsonData.create(mRawData.getData());
            mResult = mCacheAble.processRawDataFromCache(data);
        }

        private void setCurrentStatus(byte status) {
            mCurrentStatus = status;
            if (DEBUG) {
                CLog.d(LOG_TAG, "%s, setCurrentStatus: %s", mCacheAble.getCacheKey(), status);
            }
        }

        private void done() {

            long lastTime = mRawData.getTime();
            long timeInterval = System.currentTimeMillis() / 1000 - lastTime;
            boolean outOfDate = timeInterval > mCacheAble.getCacheTime() || timeInterval < 0;

            switch (mConvertFor) {
                case CONVERT_FOR_ASSERT:
                    mCacheAble.onCacheData(CacheResultType.FROM_INIT_FILE, mResult, outOfDate);
                    break;
                case CONVERT_FOR_CREATE:
                    mCacheAble.onCacheData(CacheResultType.FROM_CREATED, mResult, outOfDate);
                    break;
                case CONVERT_FOR_FILE:
                    mCacheAble.onCacheData(CacheResultType.FROM_INIT_FILE, mResult, outOfDate);
                    break;
                case CONVERT_FOR_MEMORY:
                    mCacheAble.onCacheData(CacheResultType.FROM_CACHE_FILE, mResult, outOfDate);
                    break;
            }
            if (outOfDate) {
                mCacheAble.createDataForCache(CacheManager.this);
            }
        }
    }

    private void putDataToMemoryCache(String key, CacheInfo data) {
        if (TextUtils.isEmpty(key)) {
            return;
        }
        if (DEBUG) {
            CLog.d(LOG_TAG, "%s, set cache to runtime cache list", key);
        }
        mMemoryCache.put(key, data);
    }

    /**
     * delete cache by key
     *
     * @param key
     */
    public void invalidateCache(String key) {
        if (DEBUG) {
            CLog.d(LOG_TAG, "%s, invalidateCache", key);
        }
        mFileCache.delete(key);
        mMemoryCache.remove(key);
    }

    /**
     * clear the memory cache
     */
    public void clearMemoryCache() {
        if (mMemoryCache != null) {
            mMemoryCache.evictAll();
        }
    }

    /**
     * get the spaced has been used
     *
     * @return
     */
    public int getMemoryCacheUsedSpace() {
        return mMemoryCache.size();
    }

    /**
     * get the spaced max space in config
     *
     * @return
     */
    public int getMemoryCacheMaxSpace() {
        return mMemoryCache.maxSize();
    }

    /**
     * clear the disk cache
     */
    public void clearDiskCache() {
        if (null != mFileCache) {
            mFileCache.clearCache();
        }
    }

    /**
     * return the file cache path
     *
     * @return
     */
    public String getFileCachePath() {
        if (null != mFileCache) {
            return mFileCache.getCachePath();
        }
        return null;
    }

    /**
     * get the used space in file cache
     *
     * @return
     */
    public long getFileCacheUsedSpace() {
        return null != mFileCache ? mFileCache.getUsedSpace() : 0;
    }

    /**
     * get the max space for file cache
     *
     * @return
     */
    public long getFileCacheMaxSpace() {
        if (null != mFileCache) {
            return mFileCache.getMaxSize();
        }
        return 0;
    }
}




Java Source Code List

in.srain.cube.Cube.java
in.srain.cube.app.CubeFragmentActivity.java
in.srain.cube.app.CubeFragment.java
in.srain.cube.app.FragmentParam.java
in.srain.cube.app.ICubeFragment.java
in.srain.cube.app.XActivity.java
in.srain.cube.app.lifecycle.IComponentContainer.java
in.srain.cube.app.lifecycle.LifeCycleComponentManager.java
in.srain.cube.app.lifecycle.LifeCycleComponent.java
in.srain.cube.cache.CacheInfo.java
in.srain.cube.cache.CacheManager.java
in.srain.cube.cache.CacheResultType.java
in.srain.cube.cache.ICacheAble.java
in.srain.cube.cache.IFileCache.java
in.srain.cube.cache.QueryHandler.java
in.srain.cube.cache.Query.java
in.srain.cube.concurrent.BlockingDeque.java
in.srain.cube.concurrent.Deque.java
in.srain.cube.concurrent.LinkedBlockingDeque.java
in.srain.cube.concurrent.SimpleExecutor.java
in.srain.cube.concurrent.SimpleTask.java
in.srain.cube.file.DiskLruCache.java
in.srain.cube.file.FileUtil.java
in.srain.cube.file.LruFileCache.java
in.srain.cube.image.CubeImageView.java
in.srain.cube.image.ImageLoaderFactory.java
in.srain.cube.image.ImageLoader.java
in.srain.cube.image.ImagePerformanceStatistics.java
in.srain.cube.image.ImageProvider.java
in.srain.cube.image.ImageReuseInfoManger.java
in.srain.cube.image.ImageReuseInfo.java
in.srain.cube.image.ImageTaskStatistics.java
in.srain.cube.image.ImageTask.java
in.srain.cube.image.drawable.RecyclingBitmapDrawable.java
in.srain.cube.image.drawable.RoundedDrawable.java
in.srain.cube.image.iface.ImageFileProvider.java
in.srain.cube.image.iface.ImageLoadHandler.java
in.srain.cube.image.iface.ImageLoadProgressHandler.java
in.srain.cube.image.iface.ImageMemoryCache.java
in.srain.cube.image.iface.ImageResizer.java
in.srain.cube.image.iface.ImageTaskExecutor.java
in.srain.cube.image.impl.DefaultImageLoadHandler.java
in.srain.cube.image.impl.DefaultImageResizer.java
in.srain.cube.image.impl.DefaultImageTaskExecutor.java
in.srain.cube.image.impl.DefaultMemoryCache.java
in.srain.cube.image.impl.LruImageFileProvider.java
in.srain.cube.image.impl.SimpleDownloader.java
in.srain.cube.mints.base.BlockMenuFragment.java
in.srain.cube.mints.base.DemoBaseActivity.java
in.srain.cube.mints.base.TitleBaseActivity.java
in.srain.cube.mints.base.TitleBaseFragment.java
in.srain.cube.mints.base.TitleHeaderBar.java
in.srain.cube.request.CacheAbleRequestDefaultHandler.java
in.srain.cube.request.CacheAbleRequestHandler.java
in.srain.cube.request.CacheAbleRequestJsonHandler.java
in.srain.cube.request.CacheAbleRequest.java
in.srain.cube.request.FailData.java
in.srain.cube.request.ICacheAbleRequest.java
in.srain.cube.request.IRequest.java
in.srain.cube.request.JsonData.java
in.srain.cube.request.RequestBase.java
in.srain.cube.request.RequestCacheManager.java
in.srain.cube.request.RequestData.java
in.srain.cube.request.RequestDefaultHandler.java
in.srain.cube.request.RequestFinishHandler.java
in.srain.cube.request.RequestHandler.java
in.srain.cube.request.RequestJsonHandler.java
in.srain.cube.request.SimpleJsonRequest.java
in.srain.cube.request.SimpleRequestManager.java
in.srain.cube.request.SimpleRequest.java
in.srain.cube.uri.CustomizedUri.java
in.srain.cube.util.Debug.java
in.srain.cube.util.Encrypt.java
in.srain.cube.util.Env.java
in.srain.cube.util.LocalDisplay.java
in.srain.cube.util.NetworkStatusManager.java
in.srain.cube.util.ResourceMan.java
in.srain.cube.util.SystemWatcher.java
in.srain.cube.util.Version.java
in.srain.cube.views.DotView.java
in.srain.cube.views.IScrollHeaderFrameHandler.java
in.srain.cube.views.MoreActionView.java
in.srain.cube.views.ScrollHeaderFrame.java
in.srain.cube.views.banner.BannerAdapter.java
in.srain.cube.views.banner.PagerIndicator.java
in.srain.cube.views.banner.SliderBanner.java
in.srain.cube.views.block.BlockListAdapter.java
in.srain.cube.views.block.BlockListView.java
in.srain.cube.views.list.ListPageInfo.java
in.srain.cube.views.list.ListViewDataAdapterBase.java
in.srain.cube.views.list.ListViewDataAdapter.java
in.srain.cube.views.list.PagedListDataModel.java
in.srain.cube.views.list.PagedListViewDataAdapter.java
in.srain.cube.views.list.ViewHolderBase.java
in.srain.cube.views.list.ViewHolderCreator.java
in.srain.cube.views.mix.AutoPlayer.java
in.srain.cube.views.pager.PageIndicator.java
in.srain.cube.views.pager.TabPageIndicator.java