Picasso的内存缓存机制特别棒,尤其是当你需要处理大量的图片的时候。这篇博客中,我们将介绍一下如何检验自己的定制是成功的。
Cache Indicators
如果你没有跳过之前的博客,你应该知道Picasso使用两种内存:disk和memory。也可以从网络上加载图片,这是非常耗时而且费力的做法。
作为一个开发者,研究一张图片从哪里来这是非常重要的。你可以激活cache Indicators来实现这个功能。在你的Picasso实例化之后,你只需要简单的调用.setIndicatorsEnabled(true)
就可以了。
Picasso
.with(context)
.setIndicatorsEnabled(true);
所有的图片都会在左上角标出小的标记来告诉我们图片是从哪里加载的,如图所示:
颜色表示了不同的来源:
- 绿色(memory,best performance)
- blue(disk,good performance)
- red(network,worst performance)
Logging
颜色指示器已经帮你解决了检测图片缓存的问题,但是,如果某些情况依旧不是很明确,你可以使用Logging。在Picasso实例化之后,你只需要调用.setLoggingEnabled(true)
即可。(默认情况写是faulse)
Picasso
.with(context)
.setLoggingEnabled(true);
这会导致在android logcat中输出打印的东西,(直到你调用.setLoggingEnabled(false))
) 。一旦图片开始请求,你可以在logcat中看到详细的请求输出。Picasso将会打印相关数据。
例如,picasso强制从网络上加载图片:
Picasso
.with(context)
.load(UsageExampleListViewAdapter.eatFoodyImages[2])
.memoryPolicy(MemoryPolicy.NO_CACHE)
.networkPolicy(NetworkPolicy.NO_CACHE)
.into(imageViewFromNetwork);
下面是打印输出:
D/Picasso﹕ Main created [R0] Request{http://i.imgur.com/rT5vXE1.jpg}
D/Picasso﹕ Dispatcher enqueued [R0]+21ms
D/Picasso﹕ Hunter executing [R0]+26ms
D/Picasso﹕ Hunter decoded [R0]+575ms
D/Picasso﹕ Dispatcher batched [R0]+576ms for completion
D/Picasso﹕ Main completed [R0]+807ms from NETWORK
D/Picasso﹕ Dispatcher delivered [R0]+809ms
StatsSnapshot
最后,如果你需要查看更大的图片。不是分析单个请求,而是通过观察StatsSnapshot
得到很多请求和平均结果。
为了得到数据,只需要简单的调用:
StatsSnapshot picassoStats = Picasso.with(context).getSnapshot();
这会返回一个对象,你可以在debugger里面分析或者使用Log.d("Picasso Stats", picassoStats.toString());
在logcat中打印出来。
输出会像下面那样:
D/Picasso Stats﹕ StatsSnapshot{
maxSize=28760941,
size=26567204,
cacheHits=30,
cacheMisses=58,
downloadCount=0,
totalDownloadSize=0,
averageDownloadSize=0,
totalOriginalBitmapSize=118399432,
totalTransformedBitmapSize=96928004,
averageOriginalBitmapSize=2466654,
averageTransformedBitmapSize=2019333,
originalBitmapCount=48,
transformedBitmapCount=41,
timeStamp=1432576918067}
总结
请注意上面的那些操作不能在生产环境中开启。对于一些用户来说,caching indicators看起来会很奇怪,而logging 会让你的app速度变慢。
在下一篇博客中,我们开启一个比较高级的话题:使用Picasso.Builder
改变Picasso的实例。