Volley Image Caching

后端 未结 7 2045
臣服心动
臣服心动 2020-12-09 18:18

I am trying to understand Volley\'s image caching. I have a fragment with gridview inside it, which will load around 12-30 images. There images are retrieved from server and

7条回答
  •  [愿得一人]
    2020-12-09 19:12

    A very rude way but it works :)

    package it.dataware.passaeprendi.app.util;
    
    import android.graphics.Bitmap;
    import android.graphics.BitmapFactory;
    import android.os.Environment;
    import android.util.LruCache;
    
    import com.android.volley.VolleyLog;
    import com.android.volley.toolbox.ImageLoader;
    
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.util.Date;
    
    // https://stackoverflow.com/questions/14053338/save-bitmap-in-android-as-jpeg-in-external-storage-in-a-folder
    // https://stackoverflow.com/questions/8710515/reading-an-image-file-into-bitmap-from-sdcard-why-am-i-getting-a-nullpointerexc
    
    public class DiskBitmapCache implements ImageLoader.ImageCache {
    private File   cacheDir;
    
    // ...
    private  static final String CACHE_PATH      = "dataware/passaeprendi/imagechache/";
    private  static final String CACHE_FULL_PATH = Environment.getExternalStorageDirectory() + "/" + CACHE_PATH;
    private  static final int    MAX_IMAGE_AGE   = 5; // in days
    
    private  static final BitmapFactory.Options options = new BitmapFactory.Options();
    static {
    options.inPreferredConfig = Bitmap.Config.ARGB_8888;
    }
    
    public DiskBitmapCache() {
        cacheDir = new File(CACHE_FULL_PATH);
        cacheDir.mkdirs();
    }
    
    private static  ImageLoader.ImageCache imageLoaderCache = new ImageLoader.ImageCache() {
        private final LruCache mCache = new LruCache<>(30);
    
        public void putBitmap(String url, Bitmap bitmap) {
            mCache.put(url, bitmap);
        }
        public Bitmap getBitmap(String url) {
            return mCache.get(url);
        }
    };
    
    public Bitmap getBitmap(String url) {
    
        final String volleyFileName = getFilenameForKey(url);
    
        final Bitmap bitmapL1 = imageLoaderCache.getBitmap(volleyFileName);
        if (bitmapL1 != null) {
            // VolleyLog.d("taken from cache L1 :" + url + " -> " + volleyFileName + ".");
            return bitmapL1;
        }
    
        final File volleyCacheFile = new File(cacheDir, volleyFileName);
    
        if (!volleyCacheFile.exists()) {
            return null;
        }
    
        // =======================================
        // age check
        // =======================================
    
        long diff = new Date().getTime() - volleyCacheFile.lastModified();
    
        if (diff > MAX_IMAGE_AGE * 24 * 60 * 60 * 1000) {
            volleyCacheFile.delete();
            return null;
        }
    
        // =======================================
        // load from disk
        // =======================================
    
        Bitmap bitmap = BitmapFactory.decodeFile(volleyCacheFile.getAbsolutePath(), options);
    
        if (bitmap != null) {
            //     VolleyLog.d("taken from cache L2 :" + url + " -> " + volleyFileName + ".");
            imageLoaderCache.putBitmap(volleyFileName, bitmap);
        }
    
        // VolleyLog.d("taken from cache L2 :" + url + " -> " + volleyFileName + ".");
        return bitmap;
    }
    
    public void putBitmap(String url, Bitmap bitmap) {
        final String volleyFileName = getFilenameForKey(url);
    
        File volleyCacheFile = new File(cacheDir, volleyFileName);
    
        try {
            // ...
            FileOutputStream fos = null;
            volleyCacheFile.createNewFile();
            fos = new FileOutputStream(volleyCacheFile, false);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    // Volley creates a filename for the url with the following function, so we'll use the same function
    // for translating the url back to said filename
    private String getFilenameForKey(String key) {
        int firstHalfLength = key.length() / 2;
    
        // ..
        String  localFilename   = String.valueOf(key.substring(0, firstHalfLength)  .hashCode());
                localFilename  += String.valueOf(key.substring(firstHalfLength)     .hashCode());
                localFilename  += ".jpg";
    
        return localFilename;
    }
    }    
    

    I hope will help someone.

提交回复
热议问题