使用Glide+Json缓存实现无网络下的图片显示

789 阅读1分钟

很久没写文章了,感觉还是要坚持一下啊。 因为有图片缓存本地的需求,所以这里来记录一下


#图片缓存 强大的glide是自带缓存图片的功能的,我们在加载时加上即可:


Glide.with(getActivity()).
                load(mImageDatas.get(i).getImageUrl())
                .apply(new RequestOptions()
                        .diskCacheStrategy(DiskCacheStrategy.ALL))
//ALL缓存的是原始的图片和压缩后的图片,还是一个SOURCE只缓存原始图片
                .into(imgage)

glide的缓存默认存在app的data/data/cache中 这样当我们通过url加载图片时,如果在cache中有缓存,将不加载网络图片。 #JSON缓存 因为Glide有缓存的情况下默认会读缓存,所以我们只需缓存json即可。这样当无网络时glide会读取缓存中的图片。 ##存储Json:

    private static File CacheRoot;
   public static String writeJson(Context context, String json, String fileName, boolean append) {
        CacheRoot = Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED ? context
                .getExternalCacheDir() : context.getCacheDir();
        Log.d("cachefile", "writeJson: "+CacheRoot.getAbsolutePath());
        FileOutputStream fos = null;
        ObjectOutputStream os = null;
        try {
            File cachefile = new File(CacheRoot, fileName);
            fos = new FileOutputStream(cachefile, append);
            os = new ObjectOutputStream(fos);
            if (append && cachefile.exists()) {
                FileChannel fc = fos.getChannel();
                fc.truncate(fc.position() - 4);
            }
            os.writeObject(json);

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fos != null) {

                    fos.close();


                }
                if (os != null) {


                    os.close();

                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return CacheRoot.getAbsolutePath();

    }

这段代码就能将Json串存入cache中 ##读取文件中的json

 public static String readLocalJson(Context c, String fileName){
        CacheRoot = Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED ? c
                .getExternalCacheDir() : c.getCacheDir();
        FileInputStream fis = null;
        ObjectInputStream ois = null;
//        List<String> result = new ArrayList<>();
        StringBuilder builder = new StringBuilder();
        File des = new File(CacheRoot, fileName);
        try {
            fis = new FileInputStream(des);
            ois = new ObjectInputStream(fis);
            while (fis.available() > 0)
                builder.append((String) ois.readObject());
//                result.add((String) ois.readObject());

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fis!=null)
                fis.close();
                if (ois!=null)
                ois.close();
            }catch (IOException e){
                e.printStackTrace();
            }
        }
        return builder.toString();
    }

这样在无网络状态就能缓存图片了