安卓图片异步加载开源库:Universal Image Loader

来源:互联网 发布:记事本编程是什么语言 编辑:程序博客网 时间:2024/05/16 18:31

编辑推荐:稀土掘金,这是一个针对技术开发者的一个应用,你可以在掘金上获取最新最优质的技术干货,不仅仅是Android知识、前端、后端以至于产品和设计都有涉猎,想成为全栈工程师的朋友不要错过!

Universal Image Loader 是一个开源的UI组件程序,该项目的目的是提供一个可重复使用的仪器为异步图像加载,缓存和显示。所以,如果你的程序里需要这个功能的话,那么不妨试试它。他本来是基于Fedor Vlasov's project 项目的,Universal Image Loader在此基础上做了很多修改。



下面是Universal Image Loader官方的说明文档:


开发安卓应用的过程中往往与遇到需要显示网络图片的情形。其实,在手机设备有限的内存空间和处理能力限制下,写一个这方面的程序还是比较麻烦的,要考虑多线程,缓存,内存溢出等很多方面。比如:

管理下载图片的缓存;如果图片很大,内存的利用必须高效以避免内存泄露;在远程图片的下载过程中,最好能友好的显示一张替代图片;同一张图片在一个应用中可能需要以不同的尺寸显示;等等。


如果你是自己来解决上面的所有问题,大量的时间和经历都浪费在上面提到的适配上去了。这一问题的存在促使我们开发出了一个开源的library-Universal Image Loader 来解决安卓中的图片加载。我们的目标是解决上述的所有问题,同时提供灵活的参数设置来适应尽可能多的开发者。

目前,无论是加载网络图片还是本地图片,该library都可以用。用的最多的是是用列表、表格或者gallery的方式显示网络图片。

主要特性包括:
从网络或SD卡异步加载和显示图片
在本地或内存中缓存图片
通过“listener”监视加载的过程
缓存图片至内存时,更加高效的工作
高度可定制化

ImageLoader的可选设置项

在内存中缓存的图片最大尺寸
连接超时时间和图片加载超时时间
加载图片时使用的同时工作线程数量
下载和显示图片时的线程优先级
使用已定义本地缓存或自定义
使用已定义内存缓存或自定义

图片下载的默认选项

图片加载选项可以进行以下设置:
当真实图片加载成功以后,是否显示image-stub。(如果是,需要制定stub)
在内存中是否缓存已下载图片
在本地是否缓存已下载图片
图片解码方式(最快速的方式还是少占用内存的方式)


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

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

流程图:


用法:

1.

  • Download JAR

  • libs中的 放入你的 Android project中。

2. Manifest设置

  1. <manifest>
  2. <uses-permission android:name="android.permission.INTERNET" />
  3. <!-- Include next permission if you want to allow UIL to cache images on SD card -->
  4. <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
  5. ...
  6. <application android:name="MyApplication">
  7. ...
  8. </application>
  9. </manifest>

3.application类

  1. public class MyApplication extends Application {
  2. @Override
  3. public void onCreate() {
  4. super.onCreate();
  5. // Create global configuration and initialize ImageLoader with this configuration
  6. ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext())
  7. ...
  8. .build();
  9. ImageLoader.getInstance().init(config);
  10. }
  11. }

4.配置及选项

  • ImageLoader Configuration  是整个应用的全局设置

  • Display Options 是针对每一次显示image的任务 (ImageLoader.displayImage(...))。

Configuration

每一个参数都是可选的,只设置你需要的。

  1. // DON'T COPY THIS CODE TO YOUR PROJECT! This is just example of ALL options using.
  2. File cacheDir = StorageUtils.getCacheDirectory(context);
  3. ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)
  4. .memoryCacheExtraOptions(480, 800) // default = device screen dimensions
  5. .discCacheExtraOptions(480, 800, CompressFormat.JPEG, 75)
  6. .taskExecutor(AsyncTask.THREAD_POOL_EXECUTOR)
  7. .taskExecutorForCachedImages(AsyncTask.THREAD_POOL_EXECUTOR)
  8. .threadPoolSize(3) // default
  9. .threadPriority(Thread.NORM_PRIORITY - 1) // default
  10. .tasksProcessingOrder(QueueProcessingType.FIFO) // default
  11. .denyCacheImageMultipleSizesInMemory()
  12. .memoryCache(new LruMemoryCache(2 * 1024 * 1024))
  13. .memoryCacheSize(2 * 1024 * 1024)
  14. .discCache(new UnlimitedDiscCache(cacheDir)) // default
  15. .discCacheSize(50 * 1024 * 1024)
  16. .discCacheFileCount(100)
  17. .discCacheFileNameGenerator(new HashCodeFileNameGenerator()) // default
  18. .imageDownloader(new BaseImageDownloader(context)) // default
  19. .imageDecoder(new BaseImageDecoder()) // default
  20. .defaultDisplayImageOptions(DisplayImageOptions.createSimple()) // default
  21. .enableLogging()
  22. .build();

Display 选项

  1. // DON'T COPY THIS CODE TO YOUR PROJECT! This is just example of ALL options using.
  2. DisplayImageOptions options = new DisplayImageOptions.Builder()
  3. .showStubImage(R.drawable.ic_stub)
  4. .showImageForEmptyUri(R.drawable.ic_empty)
  5. .showImageOnFail(R.drawable.ic_error)
  6. .resetViewBeforeLoading()
  7. .delayBeforeLoading(1000)
  8. .cacheInMemory()
  9. .cacheOnDisc()
  10. .preProcessor(...)
  11. .postProcessor(...)
  12. .extraForDownloader(...)
  13. .imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2) // default
  14. .bitmapConfig(Bitmap.Config.ARGB_8888) // default
  15. .decodingOptions(...)
  16. .displayer(new SimpleBitmapDisplayer()) // default
  17. .handler(new Handler()) // default
  18. .build();

下载图片支持的URL格式

  1. String imageUri = "http://site.com/image.png"; // from Web
  2. String imageUri = "file:///mnt/sdcard/image.png"; // from SD card
  3. String imageUri = "content://media/external/audio/albumart/13"; // from content provider
  4. String imageUri = "assets://image.png"; // from assets
  5. String imageUri = "drawable://" + R.drawable.image; // from drawables (only images, non-9patch)

简写方式

  1. // Load image, decode it to Bitmap and display Bitmap in ImageView
  2. imageLoader.displayImage(imageUri, imageView);


  1. // Load image, decode it to Bitmap and return Bitmap to callback
  2. imageLoader.loadImage(imageUri, new SimpleImageLoadingListener() {
  3. @Override
  4. public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
  5. // Do whatever you want with Bitmap
  6. }
  7. });


完整写法

  1. // Load image, decode it to Bitmap and display Bitmap in ImageView
  2. imageLoader.displayImage(imageUri, imageView, displayOptions, new ImageLoadingListener() {
  3. @Override
  4. public void onLoadingStarted(String imageUri, View view) {
  5. ...
  6. }
  7. @Override
  8. public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
  9. ...
  10. }
  11. @Override
  12. public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
  13. ...
  14. }
  15. @Override
  16. public void onLoadingCancelled(String imageUri, View view) {
  17. ...
  18. }
  19. });


  1. // Load image, decode it to Bitmap and return Bitmap to callback
  2. ImageSize targetSize = new ImageSize(120, 80); // result Bitmap will be fit to this size
  3. imageLoader.loadImage(imageUri, targetSize, displayOptions, new SimpleImageLoadingListener() {
  4. @Override
  5. public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
  6. // Do whatever you want with Bitmap
  7. }
  8. });

工具函数及类

  1. ImageLoader |
  2. | - getMemoryCache()
  3. | - clearMemoryCache()
  4. | - getDiscCache()
  5. | - clearDiscCache()
  6. | - denyNetworkDownloads(boolean)
  7. | - handleSlowNetwork(boolean)
  8. | - pause()
  9. | - resume()
  10. | - stop()
  11. | - destroy()
  12. | - getLoadingUriForView(ImageView)
  13. | - cancelDisplayTask(ImageView)
  14.  
  15. MemoryCacheUtil |
  16. | - findCachedBitmapsForImageUri(...)
  17. | - findCacheKeysForImageUri(...)
  18. | - removeFromCache(...)
  19.  
  20. DiscCacheUtil |
  21. | - findInCache(...)
  22. | - removeFromCache(...)
  23.  
  24. StorageUtils |
  25. | - getCacheDirectory(Context)
  26. | - getIndividualCacheDirectory(Context)
  27. | - getOwnCacheDirectory(Context, String)
  28.  
  29. PauseOnScrollListener

详情请参考 Library Map

0 0