胖虎谈ImageLoader框架(二)

2024-05-31 03:48

本文主要是介绍胖虎谈ImageLoader框架(二),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

前言

从学校出来的这半年时间,发现很少有时间可以静下来学习和写博文了,为了保持着学习和分享的习惯,我准备之后每周抽出一部分时间为大家带来一个优秀的Android框架源码阅读后的理解系列博文。

期许:希望可以和大家一起学习好此框架,也希望大家看博文前最好是先了解下框架的基本使用场景和使用方法,有什么问题可以留言给我,交流学习。
当然,再好的博文,也不如自己看一遍源码!


这周为大家带来的是《胖虎谈ImageLoader框架》系列,分析优秀的框架源码能让我们更迅速地提升,大家共勉!!
源码包下载地址:http://download.csdn.net/detail/u011133213/9210765

希望我们尊重每个人的成果,转载请注明出处。
转载于:CSDN 胖虎 , http://blog.csdn.net/ljphhj


正文

继上篇博文《胖虎谈ImageLoader框架(一)》 带来这篇《胖虎谈ImageLoader框架(二)》,上篇我们简单梳理了一下ImageLoader的3个步骤来异步加载图片,今天我们来详细看一下ImageLoader中加载图片的函数displayImage(…)和其中涉及到的一些ImageLoader框架带给我们的知识点。
(ps:读此博文前,希望网友已经阅读并理解了《胖虎谈ImageLoader框架(一)》 再阅读此博文。)

public void displayImage(String uri, ImageAware imageAware,DisplayImageOptions options, ImageLoadingListener listener,ImageLoadingProgressListener progressListener) {checkConfiguration();if (imageAware == null) {throw new IllegalArgumentException(ERROR_WRONG_ARGUMENTS);}if (listener == null) {listener = defaultListener;}if (options == null) {options = configuration.defaultDisplayImageOptions;}if (TextUtils.isEmpty(uri)) {engine.cancelDisplayTaskFor(imageAware);listener.onLoadingStarted(uri, imageAware.getWrappedView());if (options.shouldShowImageForEmptyUri()) {imageAware.setImageDrawable(options.getImageForEmptyUri(configuration.resources));} else {imageAware.setImageDrawable(null);}listener.onLoadingComplete(uri, imageAware.getWrappedView(), null);return;}ImageSize targetSize = ImageSizeUtils.defineTargetSizeForView(imageAware, configuration.getMaxImageSize());String memoryCacheKey = MemoryCacheUtils.generateKey(uri, targetSize);engine.prepareDisplayTaskFor(imageAware, memoryCacheKey);listener.onLoadingStarted(uri, imageAware.getWrappedView());Bitmap bmp = configuration.memoryCache.get(memoryCacheKey);if (bmp != null && !bmp.isRecycled()) {L.d(LOG_LOAD_IMAGE_FROM_MEMORY_CACHE, memoryCacheKey);if (options.shouldPostProcess()) {ImageLoadingInfo imageLoadingInfo = new ImageLoadingInfo(uri,imageAware, targetSize, memoryCacheKey, options,listener, progressListener, engine.getLockForUri(uri));ProcessAndDisplayImageTask displayTask = new ProcessAndDisplayImageTask(engine, bmp, imageLoadingInfo, defineHandler(options));if (options.isSyncLoading()) {displayTask.run();} else {engine.submit(displayTask);}} else {options.getDisplayer().display(bmp, imageAware,LoadedFrom.MEMORY_CACHE);listener.onLoadingComplete(uri, imageAware.getWrappedView(),bmp);}} else {if (options.shouldShowImageOnLoading()) {imageAware.setImageDrawable(options.getImageOnLoading(configuration.resources));} else if (options.isResetViewBeforeLoading()) {imageAware.setImageDrawable(null);}ImageLoadingInfo imageLoadingInfo = new ImageLoadingInfo(uri,imageAware, targetSize, memoryCacheKey, options, listener,progressListener, engine.getLockForUri(uri));LoadAndDisplayImageTask displayTask = new LoadAndDisplayImageTask(engine, imageLoadingInfo, defineHandler(options));if (options.isSyncLoading()) {displayTask.run();} else {engine.submit(displayTask);}}}

1、我们分析下函数的这几个参数:

1.1 String uri : URI,如果是网络图片(http://、https:// ),本地图片(file:// ),ContentProvider访问的(content:// ),app的Assets目录下(assets:// ),app的Drawable目录下(drawable:// )

1.2 ImageAware imageAware :
ImageView的包装类接口,实现该接口的类有:ViewAware、NonViewAware[这个为了防止加载同样的URI只回调一次而设计]

主要这边涉及到的都是ViewAware这个类:该类中中将ImageView包装放入一个WeakReference对象中,(插播一下弱引用的知识:当一个对象仅仅被WeakReference指向, 而没有任何其他StrongReference指向的时候, 如果GC运行, 那么这个对象就会被回收., 所以这样设计,ImageView就有可能会被GC回收),因此如果弱引用viewRef.get() == null, 就可以表示这个ImageView已经被GC回收了(对应的函数: ViewAware.isCollected())

ImageLoader框架的设计者考虑到了当用户要加载图片前,加载图片完成到要显示前,可能这两个时间点ImageView都已经被GC回收了,如果被回收了,这两个动作就没有必要进行了。

1.3 DisplayImageOptions options :
此类中包括的一些重要参数,系列博文第一篇中已经讲过,这边如果指定了该参数,会调用指定的来显示,或者调用之前init(…)进来的配置。

1.4ImageLoadingListener listener:
此类为加载图片的各种情况的回调监听类:onLoadingStarted, onLoadingFailed, onLoadingComplete, onLoadingCancelled

1.5 ImageLoadingProgressListener progressListener
此类为加载图片进度回调监听类:onProgressUpdate(String imageUri, View view, int current, int total) 可以用来显示某个图片加载的进度情况


2、我们分析对应代码行:
2.1 第4行 checkConfiguration() , 判断了ImageLoaderConfiguration成员变量是否被赋值,没被赋值即没调用init(…),抛异常出去,不允许继续往下执行。

	private void checkConfiguration() {if (configuration == null) {throw new IllegalStateException(ERROR_NOT_INIT);}}

2.2 第5-14行,都是为了保证参数有被正常赋值。

	if (imageAware == null) {throw new IllegalArgumentException(ERROR_WRONG_ARGUMENTS);}if (listener == null) {listener = defaultListener;}if (options == null) {options = configuration.defaultDisplayImageOptions;}

2.3 第15-27行,实际上只做了两件事,第一件事:如果是imageview的重用,现在imageview对应的uri已经为空了,那么之前未重用前的那个加载图片task,便可以从ImageLoaderEngine中取消掉了(如果还存在该task的话), 第二件事:如果开发者有设定Uri为空时要显示某张图片的话,将该图片显示到ImageView上。

	if (TextUtils.isEmpty(uri)) {engine.cancelDisplayTaskFor(imageAware);listener.onLoadingStarted(uri, imageAware.getWrappedView());if (options.shouldShowImageForEmptyUri()) {imageAware.setImageDrawable(options.getImageForEmptyUri(configuration.resources));} else {imageAware.setImageDrawable(null);}listener.onLoadingComplete(uri, imageAware.getWrappedView(), null);return;
}
	// 一个线程安全的Map, 用于控制ImageView和Uri对应上.// key: ImageView的id, // value: 图片Uri_WxH)private final Map<Integer, String> cacheKeysForImageAwares = Collections.synchronizedMap(new HashMap<Integer, String>());void cancelDisplayTaskFor(ImageAware imageAware) {cacheKeysForImageAwares.remove(imageAware.getId());}

2.4 第28-30行,获取了图片的大小(就是控件大小,如果控件大小小于屏幕大小,或者以屏幕大小为该ImageSize的大小),之后通过Uri和ImageSize,生成对应的Key值 (图片Uri_WxH),以便下面在内存缓存中查询此Key对应的Bitmap是否存在。

	ImageSize targetSize = ImageSizeUtils.defineTargetSizeForView(imageAware, configuration.getMaxImageSize());String memoryCacheKey = MemoryCacheUtils.generateKey(uri, targetSize);
	public static ImageSize defineTargetSizeForView(ImageAware imageAware, ImageSize maxImageSize) {int width = imageAware.getWidth();if (width <= 0) width = maxImageSize.getWidth();int height = imageAware.getHeight();if (height <= 0) height = maxImageSize.getHeight();return new ImageSize(width, height);}
	public static String generateKey(String imageUri, ImageSize targetSize) {return new StringBuilder(imageUri).append("_").append(targetSize.getWidth()).append("x").append(targetSize.getHeight()).toString();}

2.5 第31行,engine.prepareDisplayTaskFor(imageAware, memoryCacheKey); 这行代码看似不重要,其实很重要,大家都像ListView或者GridView等这些控件加载Adapter的,滑动时很重要的一个知识就是View重用,那么有可能当你这个ImageView要被另一张图片(另一个Uri)使用时,前面那个加载任务还没开始执行,那么那个任务怎么知道是否被重用了呢?
ImageLoader维护了一个cacheKeysForImageAwares的线程安全的HashMap,当加载图片任务要做一些加载时会去调用checkViewReused()方法去看当前要加载图片的那个ImageView匹配的是否是当前的这张图片Uri,如果不是,那么便不需要再继续往下执行这个任务了。

	void prepareDisplayTaskFor(ImageAware imageAware, String memoryCacheKey) {cacheKeysForImageAwares.put(imageAware.getId(), memoryCacheKey);}
	/** @throws TaskCancelledException if target ImageAware is collected by GC */private void checkViewReused() throws TaskCancelledException {if (isViewReused()) {throw new TaskCancelledException();}}/** @return <b>true</b> - if current ImageAware is reused for displaying another image; <b>false</b> - otherwise */private boolean isViewReused() {String currentCacheKey = engine.getLoadingUriForView(imageAware);// Check whether memory cache key (image URI) for current ImageAware is actual.// If ImageAware is reused for another task then current task should be cancelled.boolean imageAwareWasReused = !memoryCacheKey.equals(currentCacheKey);if (imageAwareWasReused) {L.d(LOG_TASK_CANCELLED_IMAGEAWARE_REUSED, memoryCacheKey);return true;}return false;}

2.6 第35-56行,主要是从内存缓存里面获取该Key值(图片Uri_WxH) 对应的Bitmap, 判断Bitmap是否存在, 如果options.shouldPostProcess(), 即上篇博文说到的,开发者设置了该值为true,表示需要在图片加载入内存中(已存在于内存中的也算这种情况),做一些额外的Process操作,这样就要开一个Task任务来执行了,执行完了再显示出图片来【ProcessAndDisplayImageTask(看源码)】。否则就直接调用开发者设置的BitmapDisplayer的对象(默认为SimpleBitmapDisplayer)显示出图片。

2.6提到的这个处理任务,看源码:ProcessAndDisplayImageTask

	if (bmp != null && !bmp.isRecycled()) {L.d(LOG_LOAD_IMAGE_FROM_MEMORY_CACHE, memoryCacheKey);if (options.shouldPostProcess()) {ImageLoadingInfo imageLoadingInfo = new ImageLoadingInfo(uri,imageAware, targetSize, memoryCacheKey, options,listener, progressListener, engine.getLockForUri(uri));ProcessAndDisplayImageTask displayTask = new ProcessAndDisplayImageTask(engine, bmp, imageLoadingInfo, defineHandler(options));if (options.isSyncLoading()) {displayTask.run();} else {engine.submit(displayTask);}} else {options.getDisplayer().display(bmp, imageAware,LoadedFrom.MEMORY_CACHE);listener.onLoadingComplete(uri, imageAware.getWrappedView(),bmp);}}

2.7 第57-73行,整个ImageLoader真正调用的入口,大部分都在这几行代码中体现了。前面几行是看是否需要为加载中的图片设置一个加载中的图片,和是否需要重置ImageView。接着是一个实体类(ImageLoadingInfo),把之后LoadAndDisplayImageTask需要用到的一些信息封装进去,接着将LoadAndDisplayImageTask任务submit到ImageLoaderEngine中(这边提的只考虑异步的情况,如果Sync同步的情况就执行执行这个Task)[PS: 具体的Task类,下一篇博文会介绍]

		if (options.shouldShowImageOnLoading()) {imageAware.setImageDrawable(options.getImageOnLoading(configuration.resources));} else if (options.isResetViewBeforeLoading()) {imageAware.setImageDrawable(null);}ImageLoadingInfo imageLoadingInfo = new ImageLoadingInfo(uri,imageAware, targetSize, 
memoryCacheKey, options, listener,progressListener, engine.getLockForUri(uri));LoadAndDisplayImageTask displayTask = new LoadAndDisplayImageTask(engine, imageLoadingInfo, defineHandler(options));if (options.isSyncLoading()) {displayTask.run();} else {engine.submit(displayTask);}

总结

其实这篇博文旨在将ImageLoader的主干入口displayImage中的一些代码行做一些解析,我不太擅于通过文字将这些东西讲得很透彻,还是那句话“要想学会框架,最终还是要自己去看看源码”,此博文中提到了几个类,我觉得都需要大家自己去看看。
(LoadAndDisplayImageTask (这个类非常重要,你需要了解该类中waitIfPaused函数,checkTaskNotActual函数,checkTaskInterrupted函数,和整个run函数是怎么运作的),
ImageLoaderEngine(你需要了解该类中包含的3个线程池各自的作用),
ProcessAndDisplayImageTask,
BitmapDisplayer,[3个子类: FadeInBitmapDisplayer、RoundedBitmapDisplayer、SimpleBitmapDisplayer]
ImageSizeUtils,[这个工具类还不错]
MemoryCacheUtils,
ImageSize)
[类的先后顺序为优先级高低,高->低]
在这里插入图片描述

这篇关于胖虎谈ImageLoader框架(二)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1017341

相关文章

Python Dash框架在数据可视化仪表板中的应用与实践记录

《PythonDash框架在数据可视化仪表板中的应用与实践记录》Python的PlotlyDash库提供了一种简便且强大的方式来构建和展示互动式数据仪表板,本篇文章将深入探讨如何使用Dash设计一... 目录python Dash框架在数据可视化仪表板中的应用与实践1. 什么是Plotly Dash?1.1

基于Flask框架添加多个AI模型的API并进行交互

《基于Flask框架添加多个AI模型的API并进行交互》:本文主要介绍如何基于Flask框架开发AI模型API管理系统,允许用户添加、删除不同AI模型的API密钥,感兴趣的可以了解下... 目录1. 概述2. 后端代码说明2.1 依赖库导入2.2 应用初始化2.3 API 存储字典2.4 路由函数2.5 应

Python GUI框架中的PyQt详解

《PythonGUI框架中的PyQt详解》PyQt是Python语言中最强大且广泛应用的GUI框架之一,基于Qt库的Python绑定实现,本文将深入解析PyQt的核心模块,并通过代码示例展示其应用场... 目录一、PyQt核心模块概览二、核心模块详解与示例1. QtCore - 核心基础模块2. QtWid

最新Spring Security实战教程之Spring Security安全框架指南

《最新SpringSecurity实战教程之SpringSecurity安全框架指南》SpringSecurity是Spring生态系统中的核心组件,提供认证、授权和防护机制,以保护应用免受各种安... 目录前言什么是Spring Security?同类框架对比Spring Security典型应用场景传统

Python结合Flask框架构建一个简易的远程控制系统

《Python结合Flask框架构建一个简易的远程控制系统》这篇文章主要为大家详细介绍了如何使用Python与Flask框架构建一个简易的远程控制系统,能够远程执行操作命令(如关机、重启、锁屏等),还... 目录1.概述2.功能使用系统命令执行实时屏幕监控3. BUG修复过程1. Authorization

SpringBoot集成图片验证码框架easy-captcha的详细过程

《SpringBoot集成图片验证码框架easy-captcha的详细过程》本文介绍了如何将Easy-Captcha框架集成到SpringBoot项目中,实现图片验证码功能,Easy-Captcha是... 目录SpringBoot集成图片验证码框架easy-captcha一、引言二、依赖三、代码1. Ea

Gin框架中的GET和POST表单处理的实现

《Gin框架中的GET和POST表单处理的实现》Gin框架提供了简单而强大的机制来处理GET和POST表单提交的数据,通过c.Query、c.PostForm、c.Bind和c.Request.For... 目录一、GET表单处理二、POST表单处理1. 使用c.PostForm获取表单字段:2. 绑定到结

修改若依框架Token的过期时间问题

《修改若依框架Token的过期时间问题》本文介绍了如何修改若依框架中Token的过期时间,通过修改`application.yml`文件中的配置来实现,默认单位为分钟,希望此经验对大家有所帮助,也欢迎... 目录修改若依框架Token的过期时间修改Token的过期时间关闭Token的过期时js间总结修改若依

MyBatis框架实现一个简单的数据查询操作

《MyBatis框架实现一个简单的数据查询操作》本文介绍了MyBatis框架下进行数据查询操作的详细步骤,括创建实体类、编写SQL标签、配置Mapper、开启驼峰命名映射以及执行SQL语句等,感兴趣的... 基于在前面几章我们已经学习了对MyBATis进行环境配置,并利用SqlSessionFactory核

cross-plateform 跨平台应用程序-03-如果只选择一个框架,应该选择哪一个?

跨平台系列 cross-plateform 跨平台应用程序-01-概览 cross-plateform 跨平台应用程序-02-有哪些主流技术栈? cross-plateform 跨平台应用程序-03-如果只选择一个框架,应该选择哪一个? cross-plateform 跨平台应用程序-04-React Native 介绍 cross-plateform 跨平台应用程序-05-Flutte