Code example for FileLruCache

Methods: interceptAndPut

0
 
    private volatile static FileLruCache imageCache;
 
    synchronized static FileLruCache getCache(Context context) throws IOException{
        if (imageCache == null) {
            imageCache = new FileLruCache(context.getApplicationContext(), TAG, new FileLruCache.Limits());
        } 
        return imageCache;
    } 
 
    // Get stream from cache, or return null if the image is not cached. 
    // Does not throw if there was an error. 
    static InputStream getCachedImageStream(URL url, Context context) {
        InputStream imageStream = null;
        if (url != null) {
            if (isCDNURL(url)) {
                try { 
                    FileLruCache cache = getCache(context);
                    imageStream = cache.get(url.toString());
                } catch (IOException e) {
                    Logger.log(LoggingBehavior.CACHE, Log.WARN, TAG, e.toString());
                } 
            } 
        } 
 
        return imageStream;
    } 
 
    static InputStream interceptAndCacheImageStream(Context context, HttpURLConnection connection) throws IOException {
        InputStream stream = null;
        if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            URL url = connection.getURL();
            stream = connection.getInputStream(); // Default stream in case caching fails
            if (isCDNURL(url)) {
                try { 
                    FileLruCache cache = getCache(context);
 
                    // Wrap stream with a caching stream 
                    stream = cache.interceptAndPut(
                            url.toString(),
                            new BufferedHttpInputStream(stream, connection));
                } catch (IOException e) {
                    // Caching is best effort 
                }