Android Glide设置和获取缓存的路径

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_39735504/article/details/79975473

1.接口GlideModule实现GlideBuider的实现类指定缓存的路径

public class GiphyGlideModule implements GlideModule {
    
    public GiphyGlideModule( ) {
    }

    @Override
    public void applyOptions(Context context, GlideBuilder builder) {
        //设置图片的显示格式ARGB_8888(指图片大小为32bit)
        builder.setDecodeFormat(DecodeFormat.PREFER_ARGB_8888);

        builder.setDiskCache(new DiskCache.Factory() {
            @Override
            public DiskCache build() {//缓存的路径
                return DiskLruCacheWrapper.get(new File(Environment.getExternalStorageDirectory(),"GlidePhoto"), 200*1000*1000);
            }
        });
    }

    @Override
    public void registerComponents(Context context, Glide glide) {

    }
}

2:在AndroidManifest中配置GiphyGlideModule

<meta-data
    android:name="包名.GiphyGlideModule"
    android:value="GlideModule" />

3.获取缓存的路径

private class getImageAsyncTask extends AsyncTask<String, Void, File> {
    private final Context context;

    public getImageAsyncTask(Context context) {
        this.context = context;
    }

    @Override
    protected File doInBackground(String... params) {
        String imgUrl =  params[0];
        Log.e("imgUrl", imgUrl);
        try {
            return Glide.with(context)
                    .load(imgUrl)
                    .downloadOnly(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
                    .get();
        } catch (Exception ex) {
            return null;
        }
    }

    @Override
    protected void onPostExecute(File result) {
        if (result == null) {
            return;
        }
        //path就是对应文件的缓存路径
        String path = result.getPath();
        Log.e("path", path);
        Bitmap bmp= BitmapFactory.decodeFile(path);
        img.setImageBitmap(bmp);

    }
}

4.调用方法

new getImageAsyncTask(AddBigImageActivity.this).execute("uri");



阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页