【转载】Picasso下载器
Github源码地址:https://github.com/JakeWharton/picasso2-okhttp3-downloader
使用方法:
Gradle:
compile 'com.jakewharton.picasso:picasso2-okhttp3-downloader:1.1.0'
调用:
OkHttpClient client = // ...
Picasso picasso = new Picasso.Builder(context)
.downloader(new OkHttp3Downloader(client))
.build()
以下是源码:(只有一个类)
package com.jakewharton.picasso; import android.content.Context;
import android.net.Uri;
import android.os.StatFs;
import com.squareup.picasso.Downloader;
import com.squareup.picasso.NetworkPolicy;
import java.io.File;
import java.io.IOException;
import okhttp3.Cache;
import okhttp3.CacheControl;
import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.ResponseBody; public final class OkHttp3Downloader implements Downloader {
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 defaultCacheDir(Context context) {
File cache = new File(context.getApplicationContext().getCacheDir(), PICASSO_CACHE);
if (!cache.exists()) {
//noinspection ResultOfMethodCallIgnored
cache.mkdirs();
}
return cache;
} private static long calculateDiskCacheSize(File dir) {
long size = MIN_DISK_CACHE_SIZE; try {
StatFs statFs = new StatFs(dir.getAbsolutePath());
long available = ((long) statFs.getBlockCount()) * statFs.getBlockSize();
// 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);
} /**
* Creates a {@link Cache} that would have otherwise been created by calling
* {@link #OkHttp3Downloader(Context)}. This allows you to build your own {@link OkHttpClient}
* while still getting the default disk cache.
*/
public static Cache createDefaultCache(Context context) {
File dir = defaultCacheDir(context);
return new Cache(dir, calculateDiskCacheSize(dir));
} private static OkHttpClient createOkHttpClient(File cacheDir, long maxSize) {
return new OkHttpClient.Builder()
.cache(new Cache(cacheDir, maxSize))
.build();
} private final Call.Factory client;
private final Cache cache; /**
* Create new downloader that uses OkHttp. This will install an image cache into your application
* cache directory.
*/
public OkHttp3Downloader(Context context) {
this(defaultCacheDir(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(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(defaultCacheDir(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(File cacheDir, long maxSize) {
this(createOkHttpClient(cacheDir, maxSize));
} public OkHttp3Downloader(OkHttpClient client) {
this.client = client;
this.cache = client.cache();
} public OkHttp3Downloader(Call.Factory client) {
this.client = client;
this.cache = null;
} @Override public Response load(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 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 (cache != null) {
try {
cache.close();
} catch (IOException ignored) {
}
}
}
}
【转载】Picasso下载器的更多相关文章
- scrapy中的下载器中间件
scrapy中的下载器中间件 下载中间件 下载器中间件是介于Scrapy的request/response处理的钩子框架. 是用于全局修改Scrapy request和response的一个轻量.底层 ...
- 转:【专题十一】实现一个基于FTP协议的程序——文件上传下载器
引言: 在这个专题将为大家揭开下FTP这个协议的面纱,其实学习知识和生活中的例子都是很相通的,就拿这个专题来说,要了解FTP协议然后根据FTP协议实现一个文件下载器,就和和追MM是差不多的过程的,相信 ...
- FPGA软件使用基础之ISE下载配置 XILINX 下载器使用
重新编辑 转载于https://www.cnblogs.com/lpp2jwz/p/7306020.html 下载程序 下载BIT 格式程序到FPGA 先插好下载器 在 ISE 中编译完 BIT 文件 ...
- 基于iOS 10、realm封装的下载器
代码地址如下:http://www.demodashi.com/demo/11653.html 概要 在决定自己封装一个下载器前,我本以为没有那么复杂,可在实际开发过程中困难重重,再加上iOS10和X ...
- 我的Android进阶之旅------>Android基于HTTP协议的多线程断点下载器的实现
一.首先写这篇文章之前,要了解实现该Android多线程断点下载器的几个知识点 1.多线程下载的原理,如下图所示 注意:由于Android移动设备和PC机的处理器还是不能相比,所以开辟的子线程建议不要 ...
- <基于Qt与POSIX线程>多线程下载器的简易搭建
原创博客,转载请联系博主! 本项目已托管到本人Git远程库:https://github.com/yue9944882/Snow 项目目标 Major Functionality 开发环境: Ce ...
- 用tkinter写出you-get下载器界面,并用pyinstaller打包成exe文件
本文为原创文章,转载请标明出处 一.you-get介绍 you-get是一个基于 python 3 的下载工具,使用 you-get 可以很轻松的下载到网络上的视频.图片及音乐.目前支持网易云音乐.A ...
- Whl自助搜索下载器
本文转载自以下链接:https://github.com/Light-City/AutoDownloadWhl 源码地址: https://github.com/Light-City/AutoDown ...
- 【Python开发】【神经网络与深度学习】网络爬虫之图片自动下载器
python爬虫实战--图片自动下载器 之前介绍了那么多基本知识[Python爬虫]入门知识(没看的赶紧去看)大家也估计手痒了.想要实际做个小东西来看看,毕竟: talk is cheap show ...
随机推荐
- OpenCV---膨胀与腐蚀
膨胀 腐蚀 一:膨胀实现dilate import cv2 as cv import numpy as np def dilate_demo(image): #膨胀 print(image.shape ...
- Web中的宽和高
不同的宽高定义 //网页可见区域宽 document.body.clientWidth //网页可见区域高 document.body.clientHeight //网页可见区域宽(包括边线和滚动条的 ...
- Tomcat面试题目
1.tomcat给你你怎样去调优? 1. JVM参数调优:-Xms<size> 表示JVM初始化堆的大小,-Xmx<size>表示JVM堆的最大值.这两个值的大小一般根据需要进 ...
- html 中的列表
html 中列表可以分为 1. 无序列表(ul--li 的形式) 2. 有序列表(ol li的形式) 3. 定义列表(dl 的形式) 下面来看几种列表的具体内容: 1.无序列表. 无序列表的格式 ...
- struts集合类型封装
1.list类型封装
- 关于SQLite3 编译及交叉编译的一些问题
from : http://blog.sina.com.cn/s/blog_5f2e119b0101ibwn.html SQLite3 (http://www.sqlite.org)是一个非常强大的小 ...
- tomcat+java的web程序持续占cpu高问题调试【转】
转自 tomcat+java的web程序持续占cpu问题调试 - 像风一样的自由 - CSDN博客http://blog.csdn.net/five3/article/details/28416771 ...
- 【转载】selenium之 定位以及切换frame(iframe)
更多关于python selenium的文章,请关注我的专栏:Python Selenium自动化测试详解 总有人看不明白,以防万一,先在开头大写加粗说明一下: frameset不用切,frame需层 ...
- vue头像上传
项目四知识点 默认头像 选择头像 <template> <div class="adatar"> <img :src="adatar?ada ...
- vsftpd.conf 详解
//不允许匿名访问 anonymous_enable=NO //设定本地用户可以访问.注意:主要是为虚拟宿主用户,如果该项目设定为NO那么所有虚拟用户将无法访问 local_enable=YES // ...