添加依赖
compile 'com.github.bumptech.glide:disklrucache:4.7.1'
同时使用okhttp实现网络请求
compile 'com.squareup.okhttp3:okhttp:3.4.1'
网络请求添加权限

<uses-permission android:name="android.permission.INTERNET"/>

网上已经有很多关于 disklrucache 的教程和使用方法,他的创建方式和之前的相同,这里不多加叙述

public void getDiskLruCache(){
        try {
            File file = getDiskCacheDir("bitmap");
            if (!file.exists()){
                file.mkdirs();
            }
            diskLruCache = DiskLruCache.open(file,getAppVersion(context),1,DISK_MAX_SIZE);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取磁盘存储路径
     * @param uniqueName
     * @return
     */
    public File getDiskCacheDir(String uniqueName){
        String cachePath;
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
                || !Environment.isExternalStorageRemovable()) {
            cachePath = context.getExternalCacheDir().getPath();
        } else {
            cachePath = context.getCacheDir().getPath();
        }
        return new File(cachePath + File.separator + uniqueName);
    }
    public int getAppVersion(Context context) {
        try {
            PackageInfo info = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            return info.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return 1;
    }

    /**
     * MD5编码
     * @param key
     * @return
     */
    public String hashKeyForDisk(String key) {
        String cacheKey;
        try {
            final MessageDigest mDigest = MessageDigest.getInstance("MD5");
            mDigest.update(key.getBytes());
            cacheKey = bytesToHexString(mDigest.digest());
        } catch (NoSuchAlgorithmException e) {
            cacheKey = String.valueOf(key.hashCode());
        }
        return cacheKey;
    }

    private String bytesToHexString(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(0xFF & bytes[i]);
            if (hex.length() == 1) {
                sb.append('0');
            }
            sb.append(hex);
        }
        return sb.toString();
    }

而不同之处在于他的实现缓存和读取缓存

在实现缓存时,用的依然是DiskLruCache.Editor editor = mDiskLruCache.edit(key),但是不再使用editor.newOutputStream,而是使用editor.getFile(0)直接获取生成一个File对象,然后将图片流写入,具体代码如下

    public Bitmap addBitmapFromHttp(String urlString){
        String key  = hashKeyForDisk(urlString);
        File file = null;
        if (diskLruCache != null){
            try {
                DiskLruCache.Editor editor = diskLruCache.edit(key);
                if (editor != null){
                    file = editor.getFile(0);
                    if (downloadUrlToFile(urlString,file)){
                        if (file.exists()){
                            editor.commit();
                        }else {
                            editor.abort();
                        }
                    }else {
                        editor.abort();
                    }
                }
                diskLruCache.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return addBitmapFromDisk(urlString);
    }
/**
     * 使用okhttp获取图片流
     * @param urlString
     * @param file
     * @return
     * @throws IOException
     */
    private boolean downloadUrlToFile(String urlString,File file) throws IOException {
        OutputStream outputStream = null;
        OkHttpClient okHttpClient = new OkHttpClient();
        InputStream inputStream = null;
        Request request = new Request.Builder()
                .url(urlString)
                .build();
        Call call = okHttpClient.newCall(request);
        try {
            outputStream = new FileOutputStream(file);
            Response response = call.execute();
            inputStream = response.body().byteStream();
            byte[] array = new byte[1024]; // 定义数组,传递流之间的数据
            int count = 0;
            outputStream = new FileOutputStream(file);
            while((count = inputStream.read(array)) != -1) {
                outputStream.write(array, 0, count);
            }
            outputStream.flush();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (inputStream != null){
                inputStream.close();
            }

            if (outputStream != null){
                outputStream.close();
            }

        }
        return false;
    }

读取缓存时,没有了Snapshot,而使用DiskLruCache.Value value = diskLruCache.get(key),也没有了getIputStream,也是直接value.getFile获取一个File对象,直接读文件。具体代码如下

    public Bitmap addBitmapFromDisk(String urlString){
        Bitmap bitmap = null;
        String key  = hashKeyForDisk(urlString);
        if (diskLruCache != null){
            try {
                DiskLruCache.Value value = diskLruCache.get(key);
                if (value != null){
                    File file = value.getFile(0);
                    FileDescriptor fd = new FileInputStream(file).getFD();
                    bitmap = BitmapFactory.decodeFileDescriptor(fd);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return bitmap;
    }
总体来说,差别并不大。
Logo

瓜分20万奖金 获得内推名额 丰厚实物奖励 易参与易上手

更多推荐