Volley core source code analysis (4)

Volley's cache


1. Disk cache
When the Volley class calls the newRequestQueue method, it creates a file

File cacheDir = new File(context.getCacheDir(), DEFAULT_CACHE_DIR);

obviously this is done Disk

cache RequestQueue queue;
        if (maxDiskCacheBytes <= -1)
        {
        // No maximum size specified
        queue = new RequestQueue(new DiskBasedCache(cacheDir), network);
        }
        else
        {
        // Disk cache size specified
        queue = new RequestQueue(new DiskBasedCache(cacheDir, maxDiskCacheBytes), network);
        }

        queue.start();

here means: when the cache size is not set, use the default cache size, otherwise use a custom size

Look at

/** Default maximum disk usage in bytes. */
    private static final int DEFAULT_DISK_USAGE_BYTES = 5 * 1024 * 1024;

Constructor;
   public DiskBasedCache(File rootDirectory) {
        this(rootDirectory, DEFAULT_DISK_USAGE_BYTES);
    }

This makes a disk cache 5M size initialization.
How the specific DiskBasedCache is cached will not be discussed here. If you are interested, you can find out for yourself. It is nothing more than saving the content to the SD card.

2. Memory cache MemoryChache

In Volley, the place I know to use memory cache is when the image is loaded, Volley defines an
interface called ImageCache,

public interface ImageCache {
        public Bitmap getBitmap(String url);
        public void putBitmap(String url ) , Bitmap bitmap);
    }

This interface defines two methods, fetch and store.

We can use LruCache or DiskChche when we implement ImageCache ourselves
But LruCache is faster to load images, followed by DiskChche;

here is a simple implementation:


public class BitmapLruCache implements ImageCache {

    private LruCache<String, Bitmap> cache;

    public BitmapLruCache() {
        cache = new LruCache<String, Bitmap> (8 * 1024 * 1024) {
            @Override
            protected int sizeOf(String key, Bitmap bitmap) {
                return bitmap.getRowBytes() * bitmap.getHeight();
            }
        };
    }

    @Override
    public Bitmap getBitmap(String url) {
        return cache .get(url);
    }

    @Override
    public void putBitmap(String url, Bitmap bitmap) {
        cache.put(url, bitmap);
    }
}

Now there are many excellent image loading libraries such as Facebook's Fresco, ImageLoader, etc.

Of course Volley's is also very useful.

3. The caching of network requests

has been completed in the previous chapters, so I won't go into details here.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326993734&siteId=291194637