开源项目Universal Image Loader for Android 说明文档

来源:互联网 发布:墨西哥留学知乎 编辑:程序博客网 时间:2024/03/29 02:21

When developing applications for Android, one often facesthe problem of displaying some graphical content from the Internet. So, youshould provide image loading from the Web in an Android app, their processingand displaying with limited memory again and again. And despite the problemhomogeneity, each new project imposes its own specific requirements on thetask.

You may need to organize caching of downloaded images; ifimages are rather large, it is necessary to ensure effective working with thememory to prevent the disastrous mistake OutOfMemoryError . It is also possiblethat an image-stub has to be showed during the image loading; and maybe thesame image should be displayed in different size variations, etc.

As a result, time and resources are wasted for codeadaptation to specific needs. It is this problem what urged me on creating alibrary with open source code - Universal Image Loader for image loading in anAndroid app. Its aim is solution universalization of the above describedproblem in a flexible and configurable tool.

Currently, the library can be used everywhere, where youhave to download and display (and possibly even to cache) an image from theInternet or from the file system of your smartphone. Classic examples forpossibility of ImageLoader using are various lists, tables, galleries, whereyou need to display images from the Web.

上面一大堆话,是说作者为什么做这个项目

现在这个类库可以用在任意地方,例如,你需要从网络上下载和显示图片,或者从手机本地读取。ImageLoader可以用的地方包括各种lists,tables,galleries

The main features of the ImageLoader for Android are:

主要特性包括:

•asynchronous loading and displaying images from the Internet or the SD-card;

从网络或SD卡异步加载和显示图片

• ability ofcaching loaded images in memory and / or the device's file system;

在本地或内存中缓存图片

• ability tomonitor the loading process by means of "listeners"

通过“listener”监视加载的过程

• effectiveworking with the memory while caching images in the memory;

缓存图片至内存时,更加高效的工作

• wideopportunities to customize the tool to fit it to your needs.

高度可定制化

ImageLoader的可选设置项

What can be configured in the ImageLoader?

全局设置:

• themaximum size of images cached in the memory;

在内存中缓存的图片最大尺寸

• timeoutfor connection establishing and image loading;

连接超时时间和图片加载超时时间

• themaximum number of simultaneously working threads for images loading;

加载图片时使用的同时工作线程数量

• threadspriority during downloading and displaying images;

下载和显示图片时的线程优先级

•implementation of disk cache (you can choose from ready-made implementations orcreate your own);

使用已定义本地缓存或自定义

•implementation of cache in the memory (you can choose from ready-madeimplementations or create your own);

使用已定义内存缓存或自定义

• default options of image downloading

图片下载的默认选项

Image loading options (applied to each individual callImageLoader.displayImage(...)) provide the ability to specify:

图片加载选项可以进行以下设置:

• whether todisplay the image-stub in the ImageView, while the real image is being loaded(if yes, then you need to specify this "stub");

当真实图片加载成功以后,是否显示image-stub。(如果是,需要制定stub)

• Whether tocache the downloaded image in the memory.

在内存中是否缓存已下载图片

• Whether tocache the downloaded image in the file system.

在本地是否缓存已下载图片

• Type ofimage decoding (the fastest or the most economical for the memory).

图片解码方式(快速/经济)

As already mentioned, you can implement your own version ofthe disk cache and the cache in memory. But most likely, you will be quitesatisfied with ready solutions, most of which are caches, limited by someparameter (size, number of files) and having their own logic of self-cleaningby limit excess (FIFO, the oldest object, the largest object, the most seldomused).

如上所述,你可以实现你自己的本地缓存和内存缓存方法,但是通常Jar包中已实现的方法已经可以满足你的需求。例如。。。。。。

There are enough configuration options, but this is not thecase as "the main principle of UNIX": "u can configureEVERYTHING. And you WILL configure everything." :) In theImageLoader case, you can customize everything, but it is not necessary at all:​​the default configuration is always available and suitable in the most cases.

尽管UIL已经提供了很多设置,但是距离“UNIX的核心精神:你可以配置任何选项,你能够配置任何选项”仍有差距。在UIL中,你可以自定义任何选项,但这并不是必须的,因为通常已经有了默认设置,而且这些设置在大多数情况下都是适用的。

Implementationpeculiarities

特定需求的实现

Few words about the project structure. Each task for image loadingand displaying (and that is, looking ahead, the call ImageLoader.displayImage(imageView, imageUrl)) is performed in a separate thread, except if the pictureis in cache in the memory - then it is just immediately displayed.here is a separate threads queue where tasks get if theneeded image is cached on the file system. If you do not have the rightimage in the cache, then the task-thread gets in the thread pool. Therefore,there are no obstacles for a fast displaying of cached images.

简单描述一下这个项目的结构。每一个图片的加载和显示任务都运行在独立的线程中,除非这个图片缓存在内存中,这种情况下图片会立即显示。如果需要的图片缓存在本地,他们会开启一个独立的线程队列。如果在缓存中没有正确的图片,任务线程会从线程池中获取,因此,快速显示缓存图片时不会有明显的障碍。

he algorithm of the taskprocessing is epresented on the scheme:

处理的规则用下图进行简单的描述:

图片说明文字

The main actors of the project can relatively be divided:

UIL的主要功能可以分为以下及部分

• the above mentionedqueue and pool of threads;

上面提到的线程队列和线程池

• cache in thememory;

缓存至内存

• disk cache;

缓存至本地

• Image decoder,which decodes image files into Bitmap objects.

图片解析,将图片解析为Bitmap对象

The main class ImageLoader manages it all; the maininteraction with the user is performed through it.

最重要的类ImageLoader管理了所有的操作,和用户的交互也主要通过该类。

All manipulations are held by the ImageLoader class. It is a singletone, so to get a single instance of the class, you should call the getInstance() method. Before using ImageLoader to its intended purpose (to display images), you should initialize its configuration - ImageLoaderConfiguration using the init (...) method. Well, then you can use all variations of the displayImage(...) method with a clear conscience.

所有的操作都由ImageLoader控制。该类使用单例设计模式,所以如果要获取该类的实力,需要调用getInstance()方法。在使用ImageLoader显示图片之前,你首先要初始化它的配置,调用ImageLoaderConfiguration的init()方法,然后你就可以实现各种的显示了。

In general, the easiest option of using ImageLoader (with the default configuration) is shown below:

通常情况下,ImageLoader最简单的使用方法如下(使用默认的配置选项):


    ImageView imageView = ... // view, where the image will be displayedString imageUrl = ... // image URL (e.g. "http://site.com/image.png", "file:///mnt/sdcard/img/image.jpg")ImageLoader imageLoader = ImageLoader.getInstance();imageLoader.init(ImageLoaderConfiguration.createDefault(context));imageLoader.displayImage(imageUrl, imageView);


Now, let’s consider the full functionality.

现在让我们讨论下他的全部功能:

As you already know, you first need to initialize the ImageLoader using the configuration object. As the ImageLoader is a singleton, then it should be initialized only once for application launching. I would recommend doing it in an overloaded Application.onCreate(). A reinitializing of an already initialized ImageLoader will have no effect.
So, we create a configuration, it is an object of the ImageLoaderConfiguration class. We create it using theBuilder:

就像你已经知道的,首先,你需要使用ImageLoaderConfiguration对象来初始化ImageLoader。由于ImageLoader是单例,所以在程序开始的时候只需要初始化一次就好了。建议你在Activity的onCreate()方法中初始化。如果一个ImageLoader已经初始化过,再次初始化不会有任何效果。下面我们通过ImageLoaderConfiguration.Builder创建一个设置

File cacheDir = StorageUtils.getCacheDirectory(context,"UniversalImageLoader/Cache");ImageLoaderConfiguration config = newImageLoaderConfiguration.Builder(getApplicationContext()).maxImageWidthForMemoryCache(800).maxImageHeightForMemoryCache(480).httpConnectTimeout(5000).httpReadTimeout(20000).threadPoolSize(5).threadPriority(Thread.MIN_PRIORITY + 3).denyCacheImageMultipleSizesInMemory().memoryCache(new UsingFreqLimitedCache(2000000)) // You can pass your own memory cache implementation.discCache(new UnlimitedDiscCache(cacheDir)) // You can pass your own disc cache implementation.defaultDisplayImageOptions(DisplayImageOptions.createSimple()).build();


Let’s consider each option:

下面上我们来讨论一下每个选项:

• maxImageWidthForMemoryCache() and maxImageHeightForMemoryCache() is used for decoding images into Bitmap objects. In order not to store a full-sized image in the memory, it is reduced to a size determined from the values of ImageView parameters, where the image is loaded: maxWidth and maxHeight (first stage),layout_width and layout_height (second stage). If these parameters are not defined (values fill_parentand wrap_content are considered as uncertain), then dimensions specified by settings maxImageWidthForMemoryCache() and maxImageHeightForMemoryCache() are taken. The size of the original image is reduced by 2 times (recommended for fast decoding), till the width or height becomes less than the specified values;

•用于将图片解码为Bitmap对象。为了避免将原图存到内存中,系统会根据ImageView的参数来缩小图片的尺寸,这些参数包括maxWidth 、maxHeight 、layout_width 、layout_height .如果这些参数没有指定,尺寸将会根据maxImageWidthForMemoryCache和maxImageHeightForMemoryCache指定。原始图片的尺寸将会被缩减两次,知道宽和高比指定的值小。

o Default values - size of the device’s screen.

o 默认值 - 设备屏幕的尺寸

• httpConnectTimeout() sets the maximum waiting time (in milliseconds) for establishing an HTTP connection;

• 设置建立HTTP连接的最大超时时间

o Default value - 5 seconds

o 默认值 - 5秒

• httpReadTimeout() sets the maximum time (in milliseconds) for loading an image from the Web;

• 设置从网络上加载图片的最大超时时间

o Default value - 30 seconds

o 默认值 - 30秒

• threadPoolSize() sets size of the thread pool. Each task on image loading and displaying is performed in a separate thread, and those threads, in which the image uploading from the Web occurs, get to the pool. Thus, the pool size determines the number of threads running simultaneously. Setting of a large pool size can significantly reduce the speed of the UI, for example, list scrolling could slow down.

• 设置线程池的大小。每一个加载和显示图片的任务都运行在独立的线程中,(囧,不知道怎么翻译)因此,线程池的大小决定了可以同时运行的线程数,如果设置的过大,将会降低UI线程的反应速度,比如List滑动时可能会卡顿。

o Default value - 5

o 默认值 - 5

• threadPriority() sets priority of all threads in the system (from 1 to 10), in which tasks are performed;

设置当前线程的优先级(1 -- 10)

o Default value - 4

o 默认值 - 4

• calling denyCacheImageMultipleSizesInMemory() imposes a ban on storing different sizes of the same image in the memory. As full-size images are stored in the disk cache, and when loading into memory, they are reduced to the size of ImageView, in which they should be displayed, then there are cases when the same image has to be displayed first in a small view, and then in a big one. At the same time, two Bitmaps of different sizes representing the same image will be stored in the memory. This is the default behavior.

•调用该方法会禁止在内存中缓存同一张图片的多个尺寸。当把本地图片加载到内存中时,首先会把图片缩减至要显示的ImageView的大小,因此可能会出现一种状况,就是会首先显示一张图的小图,然后再显示这张图的大图。这种情况下,同一张图片的两种尺寸的Bitmap会被存储在内存中,这是默认的操作

The denyCacheImageMultipleSizesInMemory() instruction ensures deletion of the previous size of the loaded image from cache in the memory.

该方法会确保删除已加载图片缓存在内存中的其他尺寸的缓存。

• Using memoryCache(), you can specify the implementation of cache in the memory. You can use ready-made solutions (they all are realizations of limited size-cache; where by exceeding cache size, an object is removed from it by a certain algorithm):

•调用该方法,你可以指定在内存中缓存的实现。你可以使用如下这些已有的解决方案

o FIFOLimitedCache (the object is removed on the basis of First-In-First-Out)

o 按照FIFO规则清理内存

o LargestLimitedCache (the largest-sized object is removed)

o 移除最大的缓存

o UsingAgeLimitedCache (the object with the oldest date of access is removed)

o 按照访问时间,移除最久之前的缓存

o UsingFreqLimitedCache (the most rarely used object is removed)

o 按照使用频率,移除最少使用的缓存

Alternatively, you can implement your own version of the cache by implementing the interface MemoryCacheAware;

当然,你也通过实现接口 MemoryCacheAware来实现一个自定义的清除缓存的方法,

o Default value - UsingFreqLimitedCache with memory limit to 2 MB

o 默认值 - UsingFreqLimitedCache ,缓存大小2MB

memoryCacheSize() sets the maximum cache size in the memory. In this case, the default cache is used -UsingFreqLimitedCache.

设置内存中缓存的大小。这种情况下,默认的缓存方法是用UsingFreqLimitedCache

o Default value - 2 MB

o 默认值 - 2MB

• Using discCache(), you can define cash implementation in the file system. You can use ready-made solutions (where the files matching certain URLs are named as hash codes of these URLs):

• discCache()设置本地缓存。你可以使用以下已实现的方法

o UnlimitedDiscCache (usual cache, no restrictions)

o 不限制缓存大小

o FileCountLimitedDiscCache (cache with limited size)

o 限制缓存的文件数量

o TotalSizeLimitedDiscCache (cache with limited files number)

o 限制缓存文件的总大小

Alternatively, you can define your own cache implementation by DiscCacheAware interface.

当然你可以实现接口DiscCacheAware 来自定义缓存的实现方法

o Default value - UnlimitedDiscCache

o 默认值 - UnlimitedDiscCache

• discCacheSize(int) specifies the maximum cache size in the file system. In this case, the TotalSizeLimitedDiscCache is used.

• 指定在本地的最大缓存大小。在这种情况下,TotalSizeLimitedDiscCache 会被使用

• discCacheFileCount(int) specifies the maximum number of files in the disk cache. In this case, the FileCountLimitedDiscCache is used.

• 指定在本地缓存的文件数量。在这种情况下,FileCountLimitedDiscCache 会被使用

• Using defaultDisplayImageOptions(), you can set image displaying options, which will be used for all calls of the displayimage(...) method, where custom options were not passed.

•使用defaultDisplayImageOptions你可以设置图片的显示选项,这些选项会在调用displayimage(...)的时候被使用。

I’ll discuss these options in details below.

在下面我会讨论这些选项

We can construct a configuration object ourselves or trust a developer (i.e. me) and use the default configuration:

我们可以自定义配置选项,也可以trust me,使用我提供的默认选项:

1
ImageLoaderConfiguration config =ImageLoaderConfiguration.createDefault(context);
Thus, the configuration is created. Now, the ImageLoader can be initialized with it:

这样,一个设置就创建了,之后,你就可以用它来初始化

1
ImageLoader.getInstance().init(config);
That's all, the ImageLoader is ready to use. I'll tell you about this in the next article.

这时候ImageLoader就可以使用了。

0 0