Picasso自定义缓存目录
项目做完终于有点自己的时间了,就想看点源码涨涨姿势,那就看看Picasso这个牛逼哄哄的图片加载框架吧,当然这个也是自己最喜欢的图片加载框架。
实际项目中可能有需求自己定制图片的缓存目录,那么就需要自定义下载器,如果我们使用with来构建Picasso 的实例的话,Picasso会通过Builder模式为我们初始化一个默认的下载器:
public Picasso build() {
Context context = this.context; if (downloader == null) {
downloader = Utils.createDefaultDownloader(context);//初始化默认下载器
}
if (cache == null) {
cache = new LruCache(context);
}
if (service == null) {
service = new PicassoExecutorService();
}
if (transformer == null) {
transformer = RequestTransformer.IDENTITY;
} Stats stats = new Stats(cache); Dispatcher dispatcher = new Dispatcher(context, service, HANDLER, downloader, cache, stats); return new Picasso(context, dispatcher, cache, listener, transformer, requestHandlers, stats,
defaultBitmapConfig, indicatorsEnabled, loggingEnabled);
}
而Picasso创建的下载器会优先使用OkHttp,如果项目没有添加OkHttp依赖的话会使用HttpUrlConnection,检查是否添加依赖使用了反射来检查:
static Downloader createDefaultDownloader(Context context) {
if (SDK_INT >= GINGERBREAD) {
try {
Class.forName("okhttp3.OkHttpClient");
return OkHttp3DownloaderCreator.create(context);
} catch (ClassNotFoundException ignored) {
}
try {
Class.forName("com.squareup.okhttp.OkHttpClient");
return OkHttpDownloaderCreator.create(context);
} catch (ClassNotFoundException ignored) {
}
}
return new UrlConnectionDownloader(context);
}
再跟踪下去,Picasso创建的默认下载器使用的缓存目录是:
static File createDefaultCacheDir(Context context) {
File cache = new File(context.getApplicationContext().getCacheDir(), PICASSO_CACHE);
if (!cache.exists()) {
//noinspection ResultOfMethodCallIgnored
cache.mkdirs();
}
return cache;
}
即data/data/packagename/...,那么我们想把图片缓存到SD卡就需要自己定义下载器并设置缓存目录,下面只是把源码稍微改了下:
import android.annotation.TargetApi;
import android.content.Context;
import android.net.Uri;
import android.os.StatFs;
import android.support.annotation.NonNull;
import android.support.annotation.VisibleForTesting; 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; import static android.os.Build.VERSION.SDK_INT;
import static android.os.Build.VERSION_CODES.JELLY_BEAN_MR2; 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) {
}
}
}
}
}
然后不要使用with实例化Picasso,而要使用builder来实例化,并设置自定义的下载器即可:
final File externalFilesDir = getExternalFilesDir(Environment.DIRECTORY_NOTIFICATIONS);
BTN.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Picasso picasso = new Picasso.Builder(MainActivity.this).downloader(new OkHttp3Downloader(externalFilesDir)).build();
picasso.load(PATH).memoryPolicy(MemoryPolicy.NO_CACHE, MemoryPolicy.NO_STORE).into(IMG);
}
});
Picasso自定义缓存目录的更多相关文章
- AppDir【创建缓存目录】
版权声明:本文为HaiyuKing原创文章,转载请注明出处! 前言 创建缓存目录 public static String APP_CACHE = "";// /storage/e ...
- AppDir【创建缓存目录】【建议使用这个工具类】
版权声明:本文为HaiyuKing原创文章,转载请注明出处! 前言 创建缓存目录 public static String APP_CACHE = "";// /storage/e ...
- .Net Core 跨平台开发实战-服务器缓存:本地缓存、分布式缓存、自定义缓存
.Net Core 跨平台开发实战-服务器缓存:本地缓存.分布式缓存.自定义缓存 1.概述 系统性能优化的第一步就是使用缓存!什么是缓存?缓存是一种效果,就是把数据结果存在某个介质中,下次直接重用.根 ...
- 【.net 深呼吸】自定义缓存配置(非Web项目)
在前一篇烂文中,老周简单讲述了非Web应用的缓存技术的基本用法.其实嘛,使用系统默认方案已经满足我们的需求了,不过,如果你真想自己来配置缓存,也是可以的. 缓存的自定义配置可以有两种方案,一种是用代码 ...
- 学习CodeIgniter框架之旅(一)自定义模板目录
在常用的框架本身都已经做好了分层和目录结构,但这在很多时候不满足项目的需求甚至在某些情况下变得不合理,因此很多时候需要自定义目录结构,在此就看看如果在CodeIgniter框架中自定义模板目录: 在C ...
- 借鉴dubbo实现自定义缓存
自定义缓存一般基于ConcurrentMap实现,实现缓存需要注意的点是缓存容器对象 本身依赖于 static final去存储对象,样例: ConcurrentMap<String, Gene ...
- Android 缓存目录 Context.getExternalFilesDir()和Context.getExternalCacheDir()方法
一.基础知识 应用程序在运行的过程中如果需要向手机上保存数据,一般是把数据保存在SDcard中的.大部分应用是直接在SDCard的根目录下创建一个文件夹,然后把数据保存在该文件夹中.这样当该应用被卸载 ...
- iOS开发——数据持久化Swift篇&文件目录路径获取(Home目录,文档目录,缓存目录等)
文件目录路径获取(Home目录,文档目录,缓存目录等) iOS应用程序只能在自己的目录下进行文件的操作,不可以访问其他的存储空间,此区域被称为沙盒.下面介绍常用的程序文件夹目录: 1,Home ...
- ueditor编辑器图片自定义存放目录及路径修改
百度编辑器ueditor功能强大,很多人士以应用项目开发中,但是里面有一个公众的问题就是上传图片存放目录太深,默认是ueditor/php/upload下,前不久测试后图片存放目录可以改变,但是路径会 ...
随机推荐
- 从日升的mecha anime看mecha genre的衰退
注:矢立肇是日升企画部集体笔名,如勇者系列便是公司企画 这里列出一些我看过认为有意思的动画,大抵同系列的就合并了,除非后续作品(剧场版,OVA,etc)并非直接剧情承接且有趣 注意我对长篇TV动画评价 ...
- python urllib2 常见请求方式
GET 添加headers头import urllib2 request = urllib2.Request(uri) request.add_header('User-Agent', 'fake-c ...
- linux内存管理2:内存映射和需求分页(英文名字:demand Paging,又叫:缺页中断)【转】
转自:http://blog.csdn.net/zhangxinrun/article/details/5873148 当某个程序映象开始运行时,可执行映象必须装入进程的虚拟地址空间.如果该程序用到了 ...
- 华为上机测试题(及格分数线-java)
PS:自己写的,自测试OK,供大家参考. /* 描述:10个学生考完期末考试评卷完成后,A老师需要划出及格线,要求如下:(1) 及格线是10的倍数:(2) 保证至少有60%的学生及格:(3) 如果所有 ...
- [Oracle] Setup DataGuard
Oracle一步步搭建DataGuard DataGuard环境: OS: SuSe 10 Primary DB: IP address:1.1.1.1 user:root passwd:****** ...
- Windows基础-使用XAudio2播放音频(本质是WASAPI)
对于常见的音频播放,使用XAudio2足够了. 时间是把杀猪刀,滑稽的是我成了猪 早在Windows Vista中,M$推出了新的音频架构UAA,其中的CoreAudio接替了DSound.WaveX ...
- Selenium2+python自动化3-解决pip使用异常【转载】
一.pip出现异常 有一小部分童鞋在打开cmd输入pip后出现下面情况:Did not provide a commandDid not provide a command?这是什么鬼?正常情况应该是 ...
- PSR-1 基础编码规范
本篇规范制定了代码基本元素的相关标准, 以确保共享的PHP代码间具有较高程度的技术互通性. 关键词 “必须”("MUST").“一定不可/一定不能”("MUST NOT& ...
- 计蒜客 28206.Runway Planning (BAPC 2014 Preliminary ACM-ICPC Asia Training League 暑假第一阶段第一场 F)
F. Runway Planning 传送门 题意简直就是有毒,中间bb一堆都是没用的,主要的意思就是度数大于180度的就先减去180度,然后除以10,四舍五入的值就是答案.如果最后结果是0就输出18 ...
- Python与数据库[2] -> 关系对象映射/ORM[3] -> sqlalchemy 的声明层 ORM 访问方式
sqlalchemy的声明层ORM访问方式 sqlalchemy中可以利用声明层进行表格类的建立,并利用ORM对象进行数据库的操作及访问,另一种方式为显式的 ORM 访问方式. 主要的建立步骤包括: ...