Android開源框架Universal-Image-Load網絡圖片加載

 Android-Universal-Image-Loader是一個開源的UI組件程序,該項目的目的是提供一個可重複使用的儀器爲異步圖像加載,緩存和顯示。

(1).使用多線程加載圖片
(2).靈活配置ImageLoader的基本參數,包括線程數、緩存方式、圖片顯示選項等;
(3).圖片異步加載緩存機制,包括內存緩存及SDCard緩存;
(4).採用監聽器監聽圖片加載過程及相應事件的處理;
(5).配置加載的圖片顯示選項,比如圖片的圓角處理及漸變動畫。

2.簡單實現

ImageLoader採用單例設計模式,ImageLoader imageLoader = ImageLoader.getInstance();得到該對象,每個ImageLoader採用單例設計模式,ImageLoader必須調用init()方法完成初始化。

  1. //  1.完成ImageLoaderConfiguration的配置  
  2. ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this)  
  3.     .memoryCacheExtraOptions(480, 800)          // default = device screen dimensions  
  4.     .discCacheExtraOptions(480, 800, CompressFormat.JPEG, 75, null)  
  5.     .taskExecutor(...)  
  6.     .taskExecutorForCachedImages(...)  
  7.     .threadPoolSize(3)                          // default  
  8.     .threadPriority(Thread.NORM_PRIORITY - 1)   // default  
  9.     .tasksProcessingOrder(QueueProcessingType.FIFO) // default  
  10.     .denyCacheImageMultipleSizesInMemory()  
  11.     .memoryCache(new LruMemoryCache(2 * 1024 * 1024))  
  12.     .memoryCacheSize(2 * 1024 * 1024)  
  13.     .memoryCacheSizePercentage(13)              // default  
  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.     .writeDebugLogs()  
  22.     .build();  
  23.   
  24. //  2.單例ImageLoader類的初始化  
  25. ImageLoader imageLoader = ImageLoader.getInstance();  
  26. imageLoader.init(config);  
  27.   
  28. //  3.DisplayImageOptions實例對象的配置  
  29. //      以下的設置再調用displayImage()有效,使用loadImage()無效  
  30. DisplayImageOptions options = new DisplayImageOptions.Builder()  
  31.     .showStubImage(R.drawable.ic_stub)          // image在加載過程中,顯示的圖片  
  32.     .showImageForEmptyUri(R.drawable.ic_empty)  // empty URI時顯示的圖片  
  33.     .showImageOnFail(R.drawable.ic_error)       // 不是圖片文件 顯示圖片  
  34.     .resetViewBeforeLoading(false)  // default  
  35.     .delayBeforeLoading(1000)  
  36.     .cacheInMemory(false)           // default 不緩存至內存  
  37.     .cacheOnDisc(false)             // default 不緩存至手機SDCard  
  38.     .preProcessor(...)  
  39.     .postProcessor(...)  
  40.     .extraForDownloader(...)  
  41.     .imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2)// default  
  42.     .bitmapConfig(Bitmap.Config.ARGB_8888)              // default  
  43.     .decodingOptions(...)  
  44.     .displayer(new SimpleBitmapDisplayer()) // default 可以設置動畫,比如圓角或者漸變  
  45.     .handler(new Handler())                             // default  
  46.     .build();  
  47.       
  48. //  4圖片加載  
  49. //  4.1 調用displayImage  
  50. imageLoader.displayImage(  
  51.     uri,        /* 
  52.                     String imageUri = "http://site.com/image.png";      // from Web 
  53.                     String imageUri = "file:///mnt/sdcard/image.png";   // from SD card 
  54.                     String imageUri = "content://media/external/audio/albumart/13"; // from content provider 
  55.                     String imageUri = "assets://image.png";             // from assets 
  56.                     */  
  57.     imageView,      // 對應的imageView控件  
  58.     options);       // 與之對應的image顯示方式選項  
  59.   
  60. //  4.2 調用loadImage  
  61. //      對於部分DisplayImageOptions對象的設置不起作用  
  62. imageLoader.loadImage(  
  63.         uri,   
  64.         options,   
  65.         new MyImageListener()); //ImageLoadingListener  
  66. class MyImageListener extends SimpleImageLoadingListener{  
  67.   
  68.     @Override  
  69.     public void onLoadingStarted(String imageUri, View view) {  
  70.         imageView.setImageResource(R.drawable.loading);  
  71.         super.onLoadingStarted(imageUri, view);  
  72.     }  
  73.   
  74.     @Override  
  75.     public void onLoadingFailed(String imageUri, View view,  
  76.             FailReason failReason) {  
  77.         imageView.setImageResource(R.drawable.no_pic);  
  78.         super.onLoadingFailed(imageUri, view, failReason);  
  79.     }  
  80.   
  81.     @Override  
  82.     public void onLoadingComplete(String imageUri, View view,  
  83.             Bitmap loadedImage) {  
  84.         imageView.setImageBitmap(loadedImage);  
  85.         super.onLoadingComplete(imageUri, view, loadedImage);  
  86.     }  
  87.   
  88.     @Override  
  89.     public void onLoadingCancelled(String imageUri, View view) {  
  90.         imageView.setImageResource(R.drawable.cancel);  
  91.         super.onLoadingCancelled(imageUri, view);  
  92.     }  
  93.       
  94. }  

3.支持的Uri

  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)  

加載drawables下圖片,可以通過ImageView.setImageResource(...) 而不是通過上面的ImageLoader.

4.緩衝至手機

默認不能保存緩存,必須通過下面的方式指定

  1. DisplayImageOptions options = new DisplayImageOptions.Builder()  
  2.         ...  
  3.         .cacheInMemory(true)  
  4.         .cacheOnDisc(true)  
  5.         ...  
  6.         .build();  
  7. ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext())  
  8.         ...  
  9.         .defaultDisplayImageOptions(options)  
  10.         ...  
  11.         .build();  
  12. ImageLoader.getInstance().init(config); // Do it on Application start  
  13.   
  14. ImageLoader.getInstance().displayImage(imageUrl, imageView);    /* 
  15.                                             默認爲defaultDisplayImageOptions設定的options對象,此處不用指定options對象 */  

或者通過下面這種方式

  1. DisplayImageOptions options = new DisplayImageOptions.Builder()  
  2.         ...  
  3.         .cacheInMemory(true)  
  4.         .cacheOnDisc(true)  
  5.         ...  
  6.         .build();  
  7. ImageLoader.getInstance().displayImage(imageUrl, imageView, options); //此處指定options對象  

由於緩存需要在外設中寫入數據,故需要添加下面的權限

  1. <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>  

5.OutOfMemoryError

如果OutOfMemoryError錯誤很常見,可以通過下面的方式設置
(1).減少configuration中線程池的線程數目(.threadPoolSize(...)) 推薦爲1 - 5
(2).display options通過.bitmapConfig(Bitmap.Config.RGB_565)設置. Bitmaps in RGB_565 consume 2 times less memory than in ARGB_8888.
(3).使用configuration的memoryCache(new WeakMemoryCache())方法 或者不調用.cacheInMemory()方法
(4).display options通過.imageScaleType(ImageScaleType.IN_SAMPLE_INT) 或者 .imageScaleType(ImageScaleType.EXACTLY)方法
(4).避免使用RoundedBitmapDisplayer,它創建了一個新的ARGB_8888 Bitmap對象

6.內存緩存管理

通過imageLoaderConfiguration.memoryCache([new LruMemoryCache(1)]))對手機內存緩存進行管理

LruMemoryCache

API >= 9默認.it is moved to the head of a queue.

FreqLimitedMemoryCache

當超過緩存大小後,刪除最近頻繁使用的bitmap

LRULimitedMemoryCache

API < 9 默認.當超過緩存大小後,刪除最近使用的bitmap

FIFOLimitedMemoryCache

FIFO rule is used for deletion when cache size limit is exceeded

LargestLimitedMemoryCache

The largest bitmap is deleted when cache size limit is exceeded

WeakMemoryCache

Unlimited cache

7.SDcard緩存管理

通過imageLoaderConfiguration.discCache([new TotalSizeLimitedDiscCache()]))對SD卡緩存進行管理

UnlimitedDiscCache

default The fastest cache, doesn't limit cache size

TotalSizeLimitedDiscCache

Cache limited by total cache size. If cache size exceeds specified limit then file with themost oldest lastusage date will be deleted

FileCountLimitedDiscCache

Cache limited by file count. If file count in cache directory exceeds specified limit then file with the most oldest last usage date will be deleted.

LimitedAgeDiscCache

Size-unlimited cache with limited files' lifetime. If age of cached file exceeds defined limit then it will be deleted from cache.

UnlimitedDiscCache is 30%-faster than other limited disc cache implementations.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章