Glide設置和獲取緩存的路徑

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");

 


 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章