最初は単純にディスクキャッシュ対応のImageCache実装を作ればおkと思ってました。実際にDiskBasedCacheを拡張した実装を作っていた記事もあったんですが気が変わりました。
/**
* 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)内で
RequestQueue queue = new RequestQueue(new DiskBasedCache(cacheDir), network);
このようにRequestQueueのインスタンスを作成してImageLoaderのコンストラクタに渡している訳です
キャッシュの容量については以下のDiskBasedCacheのコンストラクタで指定出来るようになっていますが指定しない場合にはデフォルトのキャッシュ容量(=5MB)が指定されます。
/**
* 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;
}