Android-Universal-Image-Loader文档翻译

来源:互联网 发布:dos修改java文件 编辑:程序博客网 时间:2024/06/05 15:40
Android-Universal-Image-Loader文档翻译
Introduction
When developing applications for Android, one often faces the problem of displaying some graphical content from the Internet. So, you should provide image loading from the Web in an Android app, their processing and displaying with limited memory again and again. And despite the problem homogeneity, each new project imposes its own specific requirements on the task.

介绍
开发Android应用,我们经常要面对从网上获取图片显示的问题。所以,你应该在应用里提供图片的下载,在有限的内存里反复地运行和显示。尽管是同样的问题,每一个新的项目都有它特定的需求。

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

你需要管理下载图片的缓存;如果图片很大,有必要去确保内存功效的工作,从而避免内存溢出的灾难性错误。可能我们需要在下载的过程中需要显示加载图片;可能相同的图片需要显示不同的大小等等。

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

结果,时间和资源都被浪费在适应特定的需求的编码上。这个问题促使我在Android上创建一个开源图片下载代码库-Universal Image Loader。目的是提供一个通用的解决方案通过一个弹性和可配置的工具。

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

目前,这个库可以被用在任何地方,从网上或手机的文件系统去下载和显示(甚至是缓存)。使用Classic典型的例子可能是用在列表,表格,画廊,所有需要从网上显示图片的地方。

The main features of the ImageLoader for Android are:
• asynchronous loading and displaying images from the Internet or the SD-card;
• ability of caching loaded images in memory and / or the device's file system;
• ability to monitor the loading process by means of "listeners"
• effective working with the memory while caching images in the memory;
• wide opportunities to customize the tool to fit it to your needs.

Android版的ImageLoader主要的的特点如下:
1. 从网上或SD卡上异步下载和显示图片;
2. 能够在内存或设备的文件系统里缓存下载的图片;
3. 能够监控下载的进程通过监听接口;
4. 内存高效使用,通过在内存中缓存图片;
5. 有宽泛的机会去自定义这个库去满足你的需要;

What can be configured in the ImageLoader?
Global Settings:
• the maximum size of images cached in the memory;
• timeout for connection establishing and image loading;
• the maximum number of simultaneously working threads for images loading;
• threads priority during downloading and displaying images;
• implementation of disk cache (you can choose from ready-made implementations or create your own);
• implementation of cache in the memory (you can choose from ready-made implementations or create your own);
• default options of image downloading

在ImageLoader中可以配置什么?
全局设置:
1. 在内存中缓存图片的最大大小;
2. 连接建立和图片下载的超时时间;
3. 同时下载图片的最大工作线程数量;
4. 下载和显示图片的线程优先级;
5. 磁盘缓存(你可以选择现成的实现或者创建自己的);
6. 内存缓存(你可以选择现成的实现或者创建自己的);
7. 图片下载的默认选项;

Image loading options (applied to each individual call ImageLoader.displayImage(...)) provide the ability to specify:
• whether to display the image-stub in the ImageView, while the real image is being loaded (if yes, then you need to specify this "stub");
• Whether to cache the downloaded image in the memory.
• Whether to cache the downloaded image in the file system.
• Type of image decoding (the fastest or the most economical for the memory).

图片下载选项(应用在每次调用ImageLoader.displayImage(...))提供了一些选项:
1. 当真正的图片正在下载时,是否在ImageView中显示加载图片,(如果是,你需要指定这个默认图片);
2. 是否在内存中缓存下载的图片;
3. 是否在文件系统缓存下载的图片;
4. 图片解码的类型(对内存最快或者最经济的)。

As already mentioned, you can implement your own version of the disk cache and the cache in memory. But most likely, you will be quite satisfied with ready solutions, most of which are caches, limited by some parameter (size, number of files) and having their own logic of self-cleaning by limit excess (FIFO, the oldest object, the largest object, the most seldom used).

正如已经提到的,你可以实现自己的磁盘缓存和内存缓存版本。但是,很可能,现成的解决方案就能满足你,这些缓存有,通过参数限制(大小,文件数量)和自己的自清除逻辑,通过过量限制(先进先出,最老的对象,最大的对象,最少使用)。

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

这里有足够的配置选项,但这不是像UNIX:你可以配置任何你想配置的东西。使用ImageLoader,你可以自定义任何东西,但这不是必须的:默认配置可以满足大多数的情况。

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

独特的实现
很少的描述是关于项目结构的。每一个任务的下载和显示是在一个单独的线程中执行,除了图片已经缓存在内存中,这样它会立即显示。如果任务需要显示的图片已经缓存在文件系统里,这里有一个单独的线程队列。如果在缓存中没有匹配的图片,那么任务线程会在线程池中获取。因此,没有阻碍去很快的显示缓存中的图片。

The algorithm of the task processing is simplistically represented on the scheme:


任务运行的算法在图表中简单的展示:

The main actors of the project can relatively be divided:
• the above mentioned queue and pool of threads;
• cache in the memory;
• disk cache;
• Image decoder, which decodes image files into Bitmap objects.
The main class ImageLoader manages it all; the main interaction with the user is performed through it.

In the next part, I will tell you directly about the Universal Image Loader API, as well as give some tips and advice on the use of the library.

项目的主要角色按照相关性可以分为:
1. 以上提到的队列和线程池;
2. 内存缓存;
3. 磁盘缓存;
4. 图片解码,把图片文件解码为Bitmap对象。
主要的类ImageLoader管理以上所有;主要的与用户的交互也是通过它。

在下一部分,我会告诉你关于Universal Image Loader API的目录,也会给你使用库的一些提示和建议。

UNIVERSAL IMAGE LOADER. PART 2
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之前,你需要初始化配置,通过使用init方法。这样,你可以放心地使用这个方法displayImage。

In general, the easiest option of using ImageLoader (with the default configuration) is shown below:
ImageView imageView = ... // view, where the image will be displayed
String 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);

一般,以下是使用ImageLoader(使用默认配置)最容易的配置:
ImageView imageView = ... // view, where the image will be displayed
String 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 the Builder:
File cacheDir = StorageUtils.getCacheDirectory(context,
"UniversalImageLoader/Cache");

ImageLoaderConfiguration config = new
ImageLoaderConfiguration .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();

现在,让我们考虑一下所有的功能。
正如你已经知道,你首先需要使用configuration对象初始化ImageLoader。因为ImageLoader是单例模式,所以它只能被初始化一次在应用运行时。我会建议你在Application的重载函数onCreate中去做。已经初始化了的ImageLoader再次初始化没有意义。

所以,我们创建一个configuration,ImageLoaderConfiguration类的一个对象。我们通过Builder创建它:

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_parent and 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;
o Default values - size of the device’s screen.
• httpConnectTimeout() sets the maximum waiting time (in milliseconds) for establishing an HTTP connection;
o Default value - 5 seconds
• httpReadTimeout() sets the maximum time (in milliseconds) for loading an image from the Web;
o Default value - 30 seconds

让我们考虑每一个参数:
●maxImageWidthForMemoryCache() 和 maxImageHeightForMemoryCache() 是用来把图片解码成Bitmap对象。为了不在内存中保存图片的全尺寸大小,会根据ImageView参数减小大小,图片下载完成之后,maxWidth和maxHeight(第一步),layout_width和layout_height(第二步)。如果这些参数没有定义(使用fill_parent和wrap_content被认为是不确定的),那么通过设置maxImageWidthForMemoryCache() 和 maxImageHeightForMemoryCache()指定的尺寸会被使用。原始图片大小被减小了2倍(建议使用快速解码)直到宽度或高度少于指定的值;
○默认值-设备屏幕大小
●httpConnectTimeout()设置建立HTTP连接等待的最大时间(毫秒);
○默认值-5秒
●httpReadTimeout()设置从网上下载图片最大时间(毫秒);
○默认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.
o Default value - 5
• threadPriority() sets priority of all threads in the system (from 1 to 10), in which tasks are performed;
o Default value - 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. 
The denyCacheImageMultipleSizesInMemory() instruction ensures deletion of the previous size of the loaded image from cache in the memory.

●threadPoolSize()设置线程池大小。每一个下载和显示的执行是在一个独立的线程。这样,线程池的大小决定了同时运行线程的数量。设置线程池的大小显著地减少UI的速度,例如,列表的滚动会变慢。
o 默认值是5
• threadPriority()设置任务被执行时所有线程的优先级(从1到10);
o 默认值是4
• 调用denyCacheImageMultipleSizesInMemory()强制禁止在内存存储相同图片不同的大小。所有全尺寸大小被存储在磁盘缓存中,当加载到内存时,它们会被减少到ImageView的大小,应该被显示的,有可能的情况是,相同的图片首先显示一个小的,然后显示一个大的。同时,相同图片两个不同大小的Bitmap被存储在内存中。这是默认行为。
denyCacheImageMultipleSizesInMemory()会删除掉前一个已经加载的图片大小从内存缓存里。

• 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 LargestLimitedCache (the largest-sized object is removed)
o UsingAgeLimitedCache (the object with the oldest date of access is removed)
o UsingFreqLimitedCache (the most rarely used object is removed)
Alternatively, you can implement your own version of the cache by implementing the interface MemoryCacheAware<String, Bitmap>;
o Default value - UsingFreqLimitedCache with memory limit to 2 MB
memoryCacheSize() sets the maximum cache size in the memory. In this case, the default cache is used - UsingFreqLimitedCache.
o Default value - 2 MB
• 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):
o UnlimitedDiscCache (usual cache, no restrictions)
o FileCountLimitedDiscCache (cache with limited size)
o TotalSizeLimitedDiscCache (cache with limited files number)
Alternatively, you can define your own cache implementation by DiscCacheAware interface.
o Default value - UnlimitedDiscCache

• 使用memoryCache(),你可以在内存中指定缓存的实现。你可以使用现成的解决方案(他们都是限制缓存大小的实现;通过某种算法对象很好的被移除);
o FIFOLimitedCache(对象的移除基于先进先出)
o LargestLimitedCache(最大对象被移除)
o AgeLimitedCache(最早访问对象被移除)
o FreqLimitedCache(最少访问对象被移除)或者你可以实现自己的缓存版本,通过实现接口MemoryCacheAware<String, Bitmap>;
o 默认值-使用FreqLimitedCache,内存限制大小2M
memoryCacheSize()设置内存最大缓存大小。这种情况下,默认使用UsingFreqLimitedCache。
o 默认值2M
• 使用discCache(),你可以在文件系统定义cash实现。你可以使用现成的解决方案(文件匹配URL哈希值);
o UnlimitedDiscCache(一般缓存,没有限制)
o FileCountLimitedDiscCache(限制大小的缓存)
o TotalSizeLimitedDiscCache(文件数量限制)或者你可以通过实现接口DiscCacheAware定义自己的缓存
o 默认值-UnlimitedDiscCache

• discCacheSize(int) specifies the maximum cache size in the file system. In this case, the TotalSizeLimitedDiscCache is used.
• discCacheFileCount(int) specifies the maximum number of files in the disk cache. In this case, the FileCountLimitedDiscCache is used.
• 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. 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:

ImageLoaderConfiguration config =
ImageLoaderConfiguration.createDefault(context);

Thus, the configuration is created. Now, the ImageLoader can be initialized with it:

ImageLoader.getInstance().init(config);

That's all, the ImageLoader is ready to use. I'll tell you about this in the next article.

• discCacheSize(int)指定了在文件系统最大的缓存大小。这种情况下,TotalSizeLimitedDiscCache被使用。
• discCacheFileCount(int)指定了在磁盘上缓存最大的文件数量。这种情况下,FileCountLimitedDiscCache被使用。
• defaultDisplayImageOptions(),你可以指定图片显示参数,调用displayimage(...)方法会被使用,我会在下面讨论这些参数的细节。

我们可以构造一个configuration对象或者使用默认的配置:
ImageLoaderConfiguration config =
ImageLoaderConfiguration.createDefault(context);

这样,配置被创建。现在,ImageLoader可以用它初始化:
ImageLoader.getInstance().init(config);

就这些,ImageLoader可以使用了。在下一章我会告诉你怎么使用。

UNIVERSAL IMAGE LOADER. PART 3
第三部分

In the previous article, we’ve initialized the ImageLoader with configuration; and now, it is ready for immediate use according to its intended purpose.

For this, it has four overloaded methods:
void displayImage(String url, ImageView view)
void displayImage(String url, ImageView view, DisplayImageOptions options)
void displayImage(String url, ImageView view, ImageLoadingListener listener)
void displayImage(String url, ImageView view, DisplayImageOptions options, ImageLoadingListener listener)

前几章,我们用configuration初始化了ImageLoader,现在,我们来立即使用它。

它有4个重载的方法:
void displayImage(String url, ImageView view)
void displayImage(String url, ImageView view, DisplayImageOptions options)
void displayImage(String url, ImageView view, ImageLoadingListener listener)
void displayImage(String url, ImageView view, DisplayImageOptions options, ImageLoadingListener listener)

The first option.
Everything is simple. We say, from which URL an image should be downloaded and in which ImageView it should be displayed. The view options (DisplayImageOptions) will be taken from configuration (defaultDisplayImageOptions (...)) in this case.

The second option.
We already can define certain options for a specific task. First, I’ll give an example of creating my own options: 
DisplayImageOptions options = new DisplayImageOptions.Builder()
.showStubImage(R.drawable.stub_image)
.showImageForEmptyUrl(R.drawable.image_for_empty_url)
.cacheInMemory()
.cacheOnDisc()
.decodingType(DecodingType.MEMORY_SAVING)
.build();

第一个方法。
一切都是简单的。通过URL图片可以被下载,ImageView可以显示。DisplayImageOptions参数将会被使用。

第二个方法。
我们已经定义了某种参数为一个特定的任务。首先,我会给你创建参数的例子:
DisplayImageOptions options = new DisplayImageOptions.Builder()
.showStubImage(R.drawable.stub_image)
.showImageForEmptyUrl(R.drawable.image_for_empty_url)
.cacheInMemory()
.cacheOnDisc()
.decodingType(DecodingType.MEMORY_SAVING)
.build();

Yes, Builder again. As mentioned in the first article, we can specify using DisplayImageOptions:
• whether to display the stub image in ImageView, while the real image is downloading, and what image should be displayed; 
• whether to display the stub image in ImageView if empty image URL was passed, and what image should be displayed;
• whether to cache the loaded image in memory;
• whether to cache the downloaded image on file system.
• to decode the image as quickly as possible (DecodingType.FAST) or as economical for RAM as possible (DecodingType.MEMORY_SAVING).
So, we can pass these options every time by calling displayImage() method or we can specify default options in configuration for initialization; and they will be used in all cases when options weren’t explicitly passed by method calling.

是的,再一次Builder。在第一章提到的,我们可以指定参数:
• 是否显示默认图片,当真正的图片正在下载时,显示什么图片;
• 当传了一个空的URL,是否显示默认图片;
• 是否在内存中缓存下载过的图片;
• 是否在文件系统中缓存下载过的图片;
• 解码图片是越快越好(DecodingType.FAST)还是越节约内存越好(DecodingType.MEMORY_SAVING)。
我们可以调用displayImage()方法传递不同的参数,或者可以在初始化时指定默认的参数;没有明确的传递指定的参数会被使用。

The third option.
In addition, you can "listen" the process of image downloading and displaying using the interface ImageLoadingListener:
public interface ImageLoadingListener {
void onLoadingStarted();
void onLoadingFailed();
void onLoadingComplete();
}

第三个方法。
另外,你可以监听图片下载的进程,通过接口ImageLoadingListener:
public interface ImageLoadingListener {
void onLoadingStarted();
void onLoadingFailed();
void onLoadingComplete();
}

And the fourth option is the most powerful one. You can both define options and "listen" to the process.

Tips and tricks
1. To perform its functions, the ImageLoader should receive correct parameters. And the point is ImageView rather than image URL. If you create an ImageView object in code (not using LayoutInflater), then pass the current Activity to constructor, and not the application context:
ImageView imageView = new ImageView(getApplicationContext()); // Wrong!

ImageView imageView = new ImageView(MyActivity.this); // Correctly
ImageView imageView = new ImageView(getActivity()); // Correctly (for Fragments)

2. You should configure the maxImageWidthForMemoryCache(...) and maxImageHeightForMemoryCache(...) parameters in configuration only if you want to load in the ImageView images with size larger than size of the device's screen (for example, for subsequent zooming). In all other cases, you don’t need this: these parameters consider the screen size by default for saving memory when working with Bitmaps.

第四个方法是最强大的一个。你可以使用两个,options和监听进程。

小提示
1. 为了实现它的功能,ImageLoader应该接收正确的参数。重点是ImageView而不是URL。如果你用代码创建了一个ImageView对象(不是使用LayoutInflater),传递当前Activity去构造,而不是全局应用上下文:
ImageView imageView = new ImageView(getApplicationContext()); // 错误!

ImageView imageView = new ImageView(MyActivity.this); // 正确
ImageView imageView = new ImageView(getActivity()); // 正确 (对于 Fragments)

2. 你应该配置这两个参数maxImageWidthForMemoryCache(...)和maxImageHeightForMemoryCache(...),仅仅当你想下载超过设备屏幕大小的图片(例如,缩放)。在所有其它情况,你不必这样:这些参数默认是设备屏幕大小通过保存内存。

3. Set thread pool size in the configuration wisely: a large pool size (> 10) will allow multiple threads to work simultaneously, which can significantly affect the UI work speed. But it can be fixed by setting a lower priority for threads: the lower priority is the more responsive UI is while ImageLoader work and the longer images are loaded. UI responsiveness is critical to the lists (smooth scrolling), so you should play around with setting of threadPoolSize(...) and threadPriority(...) parameters for selection of the optimal configuration for your application.

4. memoryCacheSize(...) and memoryCache(...) settings overlap each other. Use only one of them for one configuration object.

5. discCacheSize(...), discCacheFileCount(...) and discCache(...) settings overlap each other, using only one of them for one configuration object.

3. 明智的设置线程池的大小:更大的线程池大小(>10)会允许同时多个线程,但会明显的影响UI线程。但是可以设置更低的线程优先级:更低的优先级会使UI有更高的敏感性,当图片加载时。UI敏感是致命的对于列表(平滑滚动),所以你应该一起设置threadPoolSize(...)和threadPriority(...)参数为你的应用最优的配置。

4. memoryCacheSize(...) 和 memoryCache(...)互相重叠,在配置中使用一个就可以了。

5. discCacheSize(...), discCacheFileCount(...) 和 discCache(...)也互相重叠,只能选择一个。

6. If by using the ImageLoader in an application you always (or almost always) pass into the displayImage(...) method the same loading options (DisplayImageOptions), then a reasonable solution would be setting these options in the ImageLoader configuration as default options (defaultDisplayImageOptions(...) method). Then, you should not indicate these options by calling displayImage(...). If options aren’t explicitly given to the method, then default option will be used for this task.

7. There is no significant difference between FAST and MEMORY_SAVING decoding types, but it is recommended to use FAST for all kinds of lists (where you want to display many images of small size), and MEMORY_SAVING for galleries (where you want to display images of large size).

6. 如果你在应用中使用ImageLoader都是传递相同的参数,那么合理的解决方案是,在ImageLoader配置中设置参数,作为默认参数。那么,你在调用displayImage方法时不必指定这些参数。如果这些参数没有给这些方法,那么默认参数将会被使用。

7. 在解码类型FAST和MEMORY_SAVING之间没有显著的不同,但是我建议在各种列表中(当你在很小的尺寸显示大量的图片)使用FAST,在画廊(当你在很大的尺寸显示图片)中使用MEMORY_SAVING。
0 0
原创粉丝点击