LoginSignup
10
10

More than 5 years have passed since last update.

ImageLoaderをディスクキャッシュ対応にする

Posted at

最初は単純にディスクキャッシュ対応のImageCache実装を作ればおkと思ってました。実際にDiskBasedCacheを拡張した実装を作っていた記事もあったんですが気が変わりました。

ImageLoader.java
    /**
     * Simple cache adapter interface. If provided to the ImageLoader, it
     * will be used as an L1 cache before dispatch to Volley. Implementations
     * must not block. Implementation with an LruCache is recommended.
     */
    public interface ImageCache {
        public Bitmap getBitmap(String url);
        public void putBitmap(String url, Bitmap bitmap);
    }

説明には

Implementations must not block.

とあります。ディスクベースのキャッシュで読み書きするとなるとブロックしそうです。

it will be used as an L1 cache before dispatch to Volley.

ということなのでVolley内にL2キャッシュ(ディスクベース)を用意すれば上手に目的(ImageLoaderのディスクベース対応)を達成できそうです。

そう思って色々調べたところ、、

ImageLoader imageLoader = new ImageLoader(Volley.newRequestQueue(context), new BitmapCache());

と書くだけでcontext.getCacheDir()以下のディレクトリに最大5MBのディスクキャッシュが作られます。知らないうちにディスクキャッシュを使っていました(滝汗

Volley.newRequestQueue(Context, HttpStack)内で

Volley.java
        RequestQueue queue = new RequestQueue(new DiskBasedCache(cacheDir), network);

このようにRequestQueueのインスタンスを作成してImageLoaderのコンストラクタに渡している訳です

キャッシュの容量については以下のDiskBasedCacheのコンストラクタで指定出来るようになっていますが指定しない場合にはデフォルトのキャッシュ容量(=5MB)が指定されます。

DiskBasedCache.java
    /**
     * Constructs an instance of the DiskBasedCache at the specified directory.
     * @param rootDirectory The root directory of the cache.
     * @param maxCacheSizeInBytes The maximum size of the cache in bytes.
     */
    public DiskBasedCache(File rootDirectory, int maxCacheSizeInBytes) {
        mRootDirectory = rootDirectory;
        mMaxCacheSizeInBytes = maxCacheSizeInBytes;
    }
10
10
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
10