读Android Picasso源码有感

协同OKhttp、okhttp-urlconnecion自动实现硬盘缓存。

具体实现为,在Picasso进行build时,创建Downloader时,用反射去检测,如果项目集成了okhttp包,则用okhttp包中的类去创建一个OkHttpDownloader.java下载器,如果项目未集成okhttp,则使用自带的UrlConnectionDownloader.java创建。而通过查看okhttp包源代码得知,下载是利用了DiskLruCache的,由此可见Picasso结合okhttp几乎是目前最佳的网络图片解决方案了。

以下是代码:

//Below code for Picasso initializing once for the app
private Picasso picasso;
private OkHttpClient okHttpClient;

okHttpClient = new OkHttpClient();
picasso = new Picasso.Builder(this)
                .downloader(new OkHttpDownloader(okHttpClient))
                .build();

//Below code to retrieve the images whereever required on the app
picasso.with(context).load(imageUrl).placeholder(R.drawable.ic_launcher)
posted @ 2015-11-11 17:21  田红玮  阅读(138)  评论(0编辑  收藏  举报