imageLoader解析

2023-10-04 03:59
文章标签 解析 imageloader

本文主要是介绍imageLoader解析,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

ImageLoader是最早开源的 Android 图片缓存库, 强大的缓存机制, 早期使用这个图片加载框架的android应用非常多, 至今仍然有不少Android 开发者在使用。

ImagerLoader特征

  1. 支持本地、网络图片,且支持图片下载的进度监听
  2. 支持个性化配置ImagerLoader,如线程池,内存缓存策略,图片显示选项等
  3. 三层缓存加快图片的加载速度
  4. 支持图片压缩

开始使用

鉴于这篇是对ImageLoader源码来进行解析,我们首先回顾一下ImageLoader的使用。
可以通过这里下载universal-imager-loader的jar包,并将其导入到自己的项目中。
然后可以在Application或者Activity中初始化ImageLoade,参考如下:

public class YourApplication extends Application {@Overridepublic void onCreate() {super.onCreate();//创建默认的ImageLoader配置参数  ImageLoaderConfiguration configuration = ImageLoaderConfiguration  .createDefault(this);  //Initialize ImageLoader with configuration.  ImageLoader.getInstance().init(configuration);  }
}

当然,如果涉及到网络操作和磁盘缓存的话,有或者是在Application中进行初始化的话,记得要在Manifest中进行申明:

<manifest>  <uses-permission android:name="android.permission.INTERNET" />  <!-- Include next permission if you want to allow UIL to cache images on SD card -->  <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />  ...  <application android:name="YourApplication">  ...  </application>  
</manifest>  

接下来我们就可以愉快的来加载图片了,如下所示:

ImageLoader.getInstance().displayImage(imageUri, imageView);

当然,如果你想添加监听,可以这么写:

ImageLoader.getInstance().loadImage(imageUrl, new SimpleImageLoadingListener(){  @Override  public void onLoadingComplete(String imageUri, View view,  Bitmap loadedImage) {  super.onLoadingComplete(imageUri, view, loadedImage);  mImageView.setImageBitmap(loadedImage);  }  });  

至于更多的用法这里就不介绍了,如果有需要,可以参看这篇博客,了解更多关于ImageLoader的用法。下面就开始了源码的解析之路。

ImageLoaderConfiguration配置实现

我们首先还是从imageLoader的配置开始开始源码的探究之旅把。在上面的使用实例中,我们使用createDefault()方法来初始化配置,那么imageLoader的默认配置究竟是些什么呢?下面直接上代码:

public static ImageLoaderConfiguration createDefault(Context context) {return new Builder(context).build();
}public ImageLoaderConfiguration build() {initEmptyFieldsWithDefaultValues();return new ImageLoaderConfiguration(this);
}private void initEmptyFieldsWithDefaultValues() {if (taskExecutor == null) {taskExecutor = DefaultConfigurationFactory.createExecutor(threadPoolSize, threadPriority, tasksProcessingType);} else {customExecutor = true;}if (taskExecutorForCachedImages == null) {taskExecutorForCachedImages = DefaultConfigurationFactory.createExecutor(threadPoolSize, threadPriority, tasksProcessingType);} else {customExecutorForCachedImages = true;}if (diskCache == null) {if (diskCacheFileNameGenerator == null) {diskCacheFileNameGenerator = DefaultConfigurationFactory.createFileNameGenerator();}diskCache = DefaultConfigurationFactory.createDiskCache(context, diskCacheFileNameGenerator, diskCacheSize, diskCacheFileCount);}if (memoryCache == null) {memoryCache = DefaultConfigurationFactory.createMemoryCache(context, memoryCacheSize);}if (denyCacheImageMultipleSizesInMemory) {memoryCache = new FuzzyKeyMemoryCache(memoryCache, MemoryCacheUtils.createFuzzyKeyComparator());}if (downloader == null) {downloader = DefaultConfigurationFactory.createImageDownloader(context);}if (decoder == null) {decoder = DefaultConfigurationFactory.createImageDecoder(writeLogs);}if (defaultDisplayImageOptions == null) {defaultDisplayImageOptions = DisplayImageOptions.createSimple();}}
}   private ImageLoaderConfiguration(final Builder builder) {resources = builder.context.getResources();//程序本地资源访问器maxImageWidthForMemoryCache = builder.maxImageWidthForMemoryCache;//内存缓存的图片最大宽度 maxImageHeightForMemoryCache = builder.maxImageHeightForMemoryCache;//内存缓存的图片最大高度 maxImageWidthForDiskCache = builder.maxImageWidthForDiskCache;//磁盘缓存的图片最大宽度 maxImageHeightForDiskCache = builder.maxImageHeightForDiskCache;//磁盘缓存的图片最大高度 processorForDiskCache = builder.processorForDiskCache;//图片处理器,用于处理从磁盘缓存中读取到的图片 taskExecutor = builder.taskExecutor;//ImageLoaderEngine中用于执行从源获取图片任务的 Executor。taskExecutorForCachedImages = builder.taskExecutorForCachedImages;//ImageLoaderEngine中用于执行从缓存获取图片任务的 Executor。threadPoolSize = builder.threadPoolSize;//上面两个默认线程池的核心池大小,即最大并发数。threadPriority = builder.threadPriority;//上面两个默认线程池的线程优先级。tasksProcessingType = builder.tasksProcessingType;//上面两个默认线程池的线程队列类型。目前只有 FIFO, LIFO 两种可供选择。diskCache = builder.diskCache;//图片磁盘缓存,一般放在 SD 卡。memoryCache = builder.memoryCache;//图片内存缓存。defaultDisplayImageOptions = builder.defaultDisplayImageOptions;//图片显示的配置项。比如加载前、加载中、加载失败应该显示的占位图片,图片是否需要在磁盘缓存,是否需要在内存缓存等。downloader = builder.downloader;//图片下载器。decoder = builder.decoder;//图片解码器,内部可使用我们常用的BitmapFactory.decode(…)将图片资源解码成Bitmap对象。customExecutor = builder.customExecutor;//用户是否自定义了上面的 taskExecutor。customExecutorForCachedImages = builder.customExecutorForCachedImages;//用户是否自定义了上面的 taskExecutorForCachedImages。networkDeniedDownloader = new NetworkDeniedImageDownloader(downloader);//不允许访问网络的图片下载器。slowNetworkDownloader = new SlowNetworkImageDownloader(downloader);//慢网络情况下的图片下载器。L.writeDebugLogs(builder.writeLogs);
}

上面的代码有点多,但是很简单也很清晰,就是一些列初始化的代码。通过一些系列的调用,在initEmptyFieldsWithDefaultValues方法中对一些没有配置的进行的项进行配置,并通过ImageLoaderConfiguration给出默认的参数配置。对于其中的一些配置,在上面的注释中已经表明,ImageLoaderConfiguration中默认的配置,可以参考第48-73行。
至于initEmptyFieldsWithDefaultValues中的配置,在这里进行简单的介绍:
* taskExecutor 从源获取图片任务的线程池
* taskExecutorForCachedImages 用于执行从缓存获取图片任务的线程池
前面两个线程池的参数如下:

核心线程数最大线程数空闲线程等待时间容器
330sFIFO

前面两个线程池如果用户自定义的相应的线程池来实现的话,就会将customExecutor置为true,或将customExecutorForCachedImages置为true。其实customExecutor存在的意义就在于判断用户有没有自定义从源获取图片任务的线程池,customExecutorForCachedImages存在的意义判断在于用户判断用户有没有重写从缓存获取图片的线程池。
* diskCacheFileNameGenerator 默认实现为HashCodeFileNameGenerator,即用mageUri.hashCode()值当前图片名字。
* diskCache用于表示图片磁盘的缓存,默认实现为createDiskCache,默认的算法为LruDiskCache算法,缓存的目录为SD卡下的/data/data/" + context.getPackageName() + "/cache/uil-images目录下。
* memoryCache用于表示图片内存的缓存,默认实现为createMemoryCache,默认使用的算法为LruMemoryCache
* denyCacheImageMultipleSizesInMemorytrue时,表示内存缓存不允许缓存一张图片的多个尺寸。这个时候用通过FuzzyKeyMemoryCache来构建memoryCache
* downloader表示图片下载器,默认实现为createImageDownloader,最终通过BaseImageDownloader构建下载器,其下载器中重要的两个参数分别为:连接超时时间connectTimeout默认值为5分钟,读取超时时间readTimeout默认值为20分钟。
* decoder 表示图片解码器,默认实现为createImageDecoder,最终通过BaseImageDecoder实现。
* defaultDisplayImageOptions 表示默认参数,最终回调到DisplayImageOptions方法中,里面设计相关的参数初始化。这里就不展开了。

加载配置

我们首先看ApplicationimgaerLoader设置配置的方法。

 ImageLoader.getInstance().init(configuration);

接下来我们继续分析上面的代码是如何将配置应用到ImageLoader中的。首先是ImageLoader.getInstance()实例化一个ImageLoader,通过代码来看实例化的过程:

public static ImageLoader getInstance() {if (instance == null) {synchronized (ImageLoader.class) {if (instance == null) {instance = new ImageLoader();}}}return instance;
}

可以看出来,getInstance就是获取一个ImageLoader实例,运用了一个双重锁的单利模式,很简单,就不做解释了。
重点看init方法。具体在ImageLoader类中的实现如下:

public synchronized void init(ImageLoaderConfiguration configuration) {if (configuration == null) {throw new IllegalArgumentException(ERROR_INIT_CONFIG_WITH_NULL);}if (this.configuration == null) {L.d(LOG_INIT_CONFIG);engine = new ImageLoaderEngine(configuration);this.configuration = configuration;} else {L.w(WARNING_RE_INIT_CONFIG);}}

可以看出来,init的实现也是非常简单的。首先判断传入的configuration参数是否为空,为空就直接抛出一个异常,不为空就判断当前类属性configuration是否为空,类中configuration属性为空时调用ImageLoaderEngine构建engine对象,否则就打印警告日志。所以整个方法中最重要的一个语句就是new ImageLoaderEngine(configuration);。这里首先介绍一个ImageLoaderEngine类的作用。简单描述就是ImageLoaderEngine是任务分发器,负责分发LoadAndDisplayImageTaskProcessAndDisplayImageTask给具体的线程池去执行。具体实现后面会讲到。

加载图片

通过上面两个步骤,imgaeLoder的参数配置已经设置完毕,接下来我们就可以用imageLoader加载图片了。下面是三种加载图片的方式:
加载方式一,异步加载并显示图片到对应的imagerAware上

ImageLoader.getInstance().displayImage(imageUrl,imageView);

加载方式二,异步加载图片并执行回调接口

ImageLoader.getInstance().loadImage(imageUrl,new  ImageLoadingListener() {@Overridepublic void onLoadingStarted(String imageUri, View view) {}@Overridepublic void onLoadingFailed(String imageUri, View view, FailReason failReason) {}@Overridepublic void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {}

这篇关于imageLoader解析的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



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

相关文章

C语言中自动与强制转换全解析

《C语言中自动与强制转换全解析》在编写C程序时,类型转换是确保数据正确性和一致性的关键环节,无论是隐式转换还是显式转换,都各有特点和应用场景,本文将详细探讨C语言中的类型转换机制,帮助您更好地理解并在... 目录类型转换的重要性自动类型转换(隐式转换)强制类型转换(显式转换)常见错误与注意事项总结与建议类型

MySQL 缓存机制与架构解析(最新推荐)

《MySQL缓存机制与架构解析(最新推荐)》本文详细介绍了MySQL的缓存机制和整体架构,包括一级缓存(InnoDBBufferPool)和二级缓存(QueryCache),文章还探讨了SQL... 目录一、mysql缓存机制概述二、MySQL整体架构三、SQL查询执行全流程四、MySQL 8.0为何移除查

在Rust中要用Struct和Enum组织数据的原因解析

《在Rust中要用Struct和Enum组织数据的原因解析》在Rust中,Struct和Enum是组织数据的核心工具,Struct用于将相关字段封装为单一实体,便于管理和扩展,Enum用于明确定义所有... 目录为什么在Rust中要用Struct和Enum组织数据?一、使用struct组织数据:将相关字段绑

使用Java实现一个解析CURL脚本小工具

《使用Java实现一个解析CURL脚本小工具》文章介绍了如何使用Java实现一个解析CURL脚本的工具,该工具可以将CURL脚本中的Header解析为KVMap结构,获取URL路径、请求类型,解析UR... 目录使用示例实现原理具体实现CurlParserUtilCurlEntityICurlHandler

深入解析Spring TransactionTemplate 高级用法(示例代码)

《深入解析SpringTransactionTemplate高级用法(示例代码)》TransactionTemplate是Spring框架中一个强大的工具,它允许开发者以编程方式控制事务,通过... 目录1. TransactionTemplate 的核心概念2. 核心接口和类3. TransactionT

数据库使用之union、union all、各种join的用法区别解析

《数据库使用之union、unionall、各种join的用法区别解析》:本文主要介绍SQL中的Union和UnionAll的区别,包括去重与否以及使用时的注意事项,还详细解释了Join关键字,... 目录一、Union 和Union All1、区别:2、注意点:3、具体举例二、Join关键字的区别&php

Spring IOC控制反转的实现解析

《SpringIOC控制反转的实现解析》:本文主要介绍SpringIOC控制反转的实现,IOC是Spring的核心思想之一,它通过将对象的创建、依赖注入和生命周期管理交给容器来实现解耦,使开发者... 目录1. IOC的基本概念1.1 什么是IOC1.2 IOC与DI的关系2. IOC的设计目标3. IOC

java中的HashSet与 == 和 equals的区别示例解析

《java中的HashSet与==和equals的区别示例解析》HashSet是Java中基于哈希表实现的集合类,特点包括:元素唯一、无序和可包含null,本文给大家介绍java中的HashSe... 目录什么是HashSetHashSet 的主要特点是HashSet 的常用方法hasSet存储为啥是无序的

Linux中shell解析脚本的通配符、元字符、转义符说明

《Linux中shell解析脚本的通配符、元字符、转义符说明》:本文主要介绍shell通配符、元字符、转义符以及shell解析脚本的过程,通配符用于路径扩展,元字符用于多命令分割,转义符用于将特殊... 目录一、linux shell通配符(wildcard)二、shell元字符(特殊字符 Meta)三、s

使用Python实现批量访问URL并解析XML响应功能

《使用Python实现批量访问URL并解析XML响应功能》在现代Web开发和数据抓取中,批量访问URL并解析响应内容是一个常见的需求,本文将详细介绍如何使用Python实现批量访问URL并解析XML响... 目录引言1. 背景与需求2. 工具方法实现2.1 单URL访问与解析代码实现代码说明2.2 示例调用