Picasso 设置磁盘缓存

//1. 初始化
File externalFilesDir = getExternalFilesDir(Environment.DIRECTORY_NOTIFICATIONS);
        Picasso picasso = new Picasso.Builder(this)
                .downloader(new OkHttp3Downloader(externalFilesDir))//设置disk缓存
                .defaultBitmapConfig(Bitmap.Config.RGB_565) // 设置全局的图片样式
                .loggingEnabled(true)       //log
                .build();
        Picasso.setSingletonInstance(picasso); // 设置Picasso单例
复制代码
//0. 缓存类
public final class OkHttp3Downloader implements Downloader {
    private final Call.Factory client;
    private final Cache cache;
    private boolean sharedClient = true;
    private static final String PICASSO_CACHE = "picasso-cache";
    private static final int MIN_DISK_CACHE_SIZE = 5 * 1024 * 1024; // 5MB
    private static final int MAX_DISK_CACHE_SIZE = 50 * 1024 * 1024; // 50MB

    private static File createDefaultCacheDir(Context context) {
        File cache = new File(context.getApplicationContext().getCacheDir(), PICASSO_CACHE);
        if (!cache.exists()) {
            //noinspection ResultOfMethodCallIgnored
            cache.mkdirs();
        }
        return cache;
    }

    @TargetApi(JELLY_BEAN_MR2)
    private static long calculateDiskCacheSize(File dir) {
        long size = MIN_DISK_CACHE_SIZE;

        try {
            StatFs statFs = new StatFs(dir.getAbsolutePath());
            //noinspection deprecation
            long blockCount = SDK_INT < JELLY_BEAN_MR2 ? (long) statFs.getBlockCount() : statFs.getBlockCountLong();
            //noinspection deprecation
            long blockSize = SDK_INT < JELLY_BEAN_MR2 ? (long) statFs.getBlockSize() : statFs.getBlockSizeLong();
            long available = blockCount * blockSize;
            // Target 2% of the total space.
            size = available / 50;
        } catch (IllegalArgumentException ignored) {
        }

        // Bound inside min/max size for disk cache.
        return Math.max(Math.min(size, MAX_DISK_CACHE_SIZE), MIN_DISK_CACHE_SIZE);
    }

    /**
     * Create new downloader that uses OkHttp. This will install an image cache into your application
     * cache directory.
     */
    public OkHttp3Downloader(final Context context) {
        this(createDefaultCacheDir(context));
    }

    /**
     * Create new downloader that uses OkHttp. This will install an image cache into the specified
     * directory.
     *
     * @param cacheDir The directory in which the cache should be stored
     */
    public OkHttp3Downloader(final File cacheDir) {
        this(cacheDir, calculateDiskCacheSize(cacheDir));
    }

    /**
     * Create new downloader that uses OkHttp. This will install an image cache into your application
     * cache directory.
     *
     * @param maxSize The size limit for the cache.
     */
    public OkHttp3Downloader(final Context context, final long maxSize) {
        this(createDefaultCacheDir(context), maxSize);
    }

    /**
     * Create new downloader that uses OkHttp. This will install an image cache into the specified
     * directory.
     *
     * @param cacheDir The directory in which the cache should be stored
     * @param maxSize  The size limit for the cache.
     */
    public OkHttp3Downloader(final File cacheDir, final long maxSize) {
        this(new OkHttpClient.Builder().cache(new Cache(cacheDir, maxSize)).build());
        sharedClient = false;
    }

    /**
     * Create a new downloader that uses the specified OkHttp instance. A response cache will not be
     * automatically configured.
     */
    public OkHttp3Downloader(OkHttpClient client) {
        this.client = client;
        this.cache = client.cache();
    }

    /**
     * Create a new downloader that uses the specified {@link Call.Factory} instance.
     */
    public OkHttp3Downloader(Call.Factory client) {
        this.client = client;
        this.cache = null;
    }

    @VisibleForTesting
    Cache getCache() {
        return ((OkHttpClient) client).cache();
    }

    @Override
    public Response load(@NonNull Uri uri, int networkPolicy) throws IOException {
        CacheControl cacheControl = null;
        if (networkPolicy != 0) {
            if (NetworkPolicy.isOfflineOnly(networkPolicy)) {
                cacheControl = CacheControl.FORCE_CACHE;
            } else {
                CacheControl.Builder builder = new CacheControl.Builder();
                if (!NetworkPolicy.shouldReadFromDiskCache(networkPolicy)) {
                    builder.noCache();
                }
                if (!NetworkPolicy.shouldWriteToDiskCache(networkPolicy)) {
                    builder.noStore();
                }
                cacheControl = builder.build();
            }
        }

        Request.Builder builder = new okhttp3.Request.Builder().url(uri.toString());
        if (cacheControl != null) {
            builder.cacheControl(cacheControl);
        }

        okhttp3.Response response = client.newCall(builder.build()).execute();
        int responseCode = response.code();
        if (responseCode >= 300) {
            response.body().close();
            throw new ResponseException(responseCode + " " + response.message(), networkPolicy,
                    responseCode);
        }

        boolean fromCache = response.cacheResponse() != null;

        ResponseBody responseBody = response.body();
        return new Response(responseBody.byteStream(), fromCache, responseBody.contentLength());
    }

    @Override
    public void shutdown() {
        if (!sharedClient) {
            if (cache != null) {
                try {
                    cache.close();
                } catch (IOException ignored) {
                }
            }
        }
    }
}
复制代码

转载于:https://juejin.im/post/5a31ee486fb9a044ff3179c4

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Picasso – Android系统的图片下载和缓存类库 Picasso 是Square开源的一个用于Android系统下载和缓存图片的项目。该项目和其他一些下载图片项目的主要区别之一是:使用4.0+系统上的HTTP缓存来代替磁盘缓存Picasso 的使用是非常简单的,例如: 帮助 1 Picasso.with(context).load("http://i.imgur.com/DvpvklR.png.into(imageView")); Picasso有如下特性: 处理Adapter中的 ImageView 回收和取消已经回收ImageView的下载进程 使用最少的内存完成复杂的图片转换,比如把下载的图片转换为圆角等 自动添加磁盘和内存缓存 具体介绍 在Adapter中下载 自动检测Adapter中的ImageView重用和取消不必要的下载 帮助 01.@Override public void getView(int position, View convertView, ViewGroup parent) { 02.SquaredImageView view = (SquaredImageView) convertView; 03.if (view == null) { 04.view = new SquaredImageView(context); 05.} 06.String url = getItem(position);Picasso.with(context).load(url).into(view); 07.} 复制代码 图片转换 转换图片以适合所显示的ImageView,来减少内存消耗 帮助 01.Picasso.with(context) 02..load(url) 03..resize(50, 50) 04..centerCrop() 05..into(imageView) 复制代码 还可以设置自定义转换来实现高级效果,例如下面的矩形特效(把图片居中裁剪为矩形) 帮助 01.public class CropSquareTransformation implements Transformation { 02.@Override public Bitmap transform(Bitmap source) { 03.int size = Math.min(source.getWidth(), source.getHeight()); 04.int x = (source.getWidth() - size) / 2; 05.int y = (source.getHeight() - size) / 2; 06.Bitmap result = Bitmap.createBitmap(source, x, y, size, size); 07.if (result != source) { 08.source.recycle(); 09.} 10.return result; 11.}@Override public String key() { return "square()"; } 12.} 复制代码 用该类示例调用函数 RequestBuilder.transform(Transformation) 即可。 占位符图片 Picasso支持下载和加载错误占位符图片。 帮助 Picasso.with(context) .load(url) .placeholder(R.drawable.user_placeholder) .error(R.drawable.user_placeholder_error) .into(imageView); 如果重试3次(下载源代码可以根据需要修改)还是无法成功加载图片 则用错误占位符图片显示。 支持本地资源加载 从 Resources, assets, files, content providers 加载图片都支持 Picasso.with(context).load(R.drawable.landing_screen).into(imageView1); Picasso.with(context).load(new File("/images/oprah_bees.gif")).into(imageView2); 调试支持 调用函数 Picasso.setDebug(true) 可以在加载的图片左上角显示一个 三角形 ,不同的颜色代表加载的来源 红色:代表从网络下载的图片 黄色:代表从磁盘缓存加载的图片 绿色:代表从内存中加载的图片 如果项目中使用了OkHttp库的话,默认会使用OkHttp来下载图片。否则使用HttpUrlConnection来下载图片
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值