開源框架Universal-Image-Loader完全解析



---------------------------------------------------------------------基礎部分--------------------------------------------------------------------------



轉載請註明本文出自xiaanming的博客(http://blog.csdn.net/xiaanming/article/details/26810303),請尊重他人的辛勤勞動成果,謝謝!

大家好!差不多兩個來月沒有寫文章了,前段時間也是在忙換工作的事,準備筆試面試什麼的事情,現在新工作找好了,新工作自己也比較滿意,唯一遺憾的就是自己要去一個新的城市,新的環境新的開始,希望自己能儘快的適應新環境,現在在準備交接的事情,自己也有一些時間了,所以就繼續給大家分享Android方面的東西。

相信大家平時做Android應用的時候,多少會接觸到異步加載圖片,或者加載大量圖片的問題,而加載圖片我們常常會遇到許多的問題,比如說圖片的錯亂,OOM等問題,對於新手來說,這些問題解決起來會比較喫力,所以就有很多的開源圖片加載框架應運而生,比較著名的就是Universal-Image-Loader,相信很多朋友都聽過或者使用過這個強大的圖片加載框架,今天這篇文章就是對這個框架的基本介紹以及使用,主要是幫助那些沒有使用過這個框架的朋友們。該項目存在於Github上面https://github.com/nostra13/Android-Universal-Image-Loader,我們可以先看看這個開源庫存在哪些特徵

  1. 多線程下載圖片,圖片可以來源於網絡,文件系統,項目文件夾assets中以及drawable中等
  2. 支持隨意的配置ImageLoader,例如線程池,圖片下載器,內存緩存策略,硬盤緩存策略,圖片顯示選項以及其他的一些配置
  3. 支持圖片的內存緩存,文件系統緩存或者SD卡緩存
  4. 支持圖片下載過程的監聽
  5. 根據控件(ImageView)的大小對Bitmap進行裁剪,減少Bitmap佔用過多的內存
  6. 較好的控制圖片的加載過程,例如暫停圖片加載,重新開始加載圖片,一般使用在ListView,GridView中,滑動過程中暫停加載圖片,停止滑動的時候去加載圖片
  7. 提供在較慢的網絡下對圖片進行加載

當然上面列舉的特性可能不全,要想了解一些其他的特性只能通過我們的使用慢慢去發現了,接下來我們就看看這個開源庫的簡單使用吧


新建一個Android項目,下載JAR包添加到工程libs目錄下

新建一個MyApplication繼承Application,並在onCreate()中創建ImageLoader的配置參數,並初始化到ImageLoader中代碼如下

  1. package com.example.uil;  
  2.   
  3. import com.nostra13.universalimageloader.core.ImageLoader;  
  4. import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;  
  5.   
  6. import android.app.Application;  
  7.   
  8. public class MyApplication extends Application {  
  9.   
  10.     @Override  
  11.     public void onCreate() {  
  12.         super.onCreate();  
  13.   
  14.         //創建默認的ImageLoader配置參數  
  15.         ImageLoaderConfiguration configuration = ImageLoaderConfiguration  
  16.                 .createDefault(this);  
  17.           
  18.         //Initialize ImageLoader with configuration.  
  19.         ImageLoader.getInstance().init(configuration);  
  20.     }  
  21.   
  22. }  
package com.example.uil;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;

import android.app.Application;

public class MyApplication extends Application {

	@Override
	public void onCreate() {
		super.onCreate();

		//創建默認的ImageLoader配置參數
		ImageLoaderConfiguration configuration = ImageLoaderConfiguration
				.createDefault(this);
		
		//Initialize ImageLoader with configuration.
		ImageLoader.getInstance().init(configuration);
	}

}
ImageLoaderConfiguration是圖片加載器ImageLoader的配置參數,使用了建造者模式,這裏是直接使用了createDefault()方法創建一個默認的ImageLoaderConfiguration,當然我們還可以自己設置ImageLoaderConfiguration,設置如下

  1. File cacheDir = StorageUtils.getCacheDirectory(context);  
  2. ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)  
  3.         .memoryCacheExtraOptions(480800// default = device screen dimensions  
  4.         .diskCacheExtraOptions(480800, CompressFormat.JPEG, 75null)  
  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.         .diskCache(new UnlimitedDiscCache(cacheDir)) // default  
  15.         .diskCacheSize(50 * 1024 * 1024)  
  16.         .diskCacheFileCount(100)  
  17.         .diskCacheFileNameGenerator(new HashCodeFileNameGenerator()) // default  
  18.         .imageDownloader(new BaseImageDownloader(context)) // default  
  19.         .imageDecoder(new BaseImageDecoder()) // default  
  20.         .defaultDisplayImageOptions(DisplayImageOptions.createSimple()) // default  
  21.         .writeDebugLogs()  
  22.         .build();  
File cacheDir = StorageUtils.getCacheDirectory(context);
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)
        .memoryCacheExtraOptions(480, 800) // default = device screen dimensions
        .diskCacheExtraOptions(480, 800, CompressFormat.JPEG, 75, null)
        .taskExecutor(...)
        .taskExecutorForCachedImages(...)
        .threadPoolSize(3) // default
        .threadPriority(Thread.NORM_PRIORITY - 1) // default
        .tasksProcessingOrder(QueueProcessingType.FIFO) // default
        .denyCacheImageMultipleSizesInMemory()
        .memoryCache(new LruMemoryCache(2 * 1024 * 1024))
        .memoryCacheSize(2 * 1024 * 1024)
        .memoryCacheSizePercentage(13) // default
        .diskCache(new UnlimitedDiscCache(cacheDir)) // default
        .diskCacheSize(50 * 1024 * 1024)
        .diskCacheFileCount(100)
        .diskCacheFileNameGenerator(new HashCodeFileNameGenerator()) // default
        .imageDownloader(new BaseImageDownloader(context)) // default
        .imageDecoder(new BaseImageDecoder()) // default
        .defaultDisplayImageOptions(DisplayImageOptions.createSimple()) // default
        .writeDebugLogs()
        .build();

上面的這些就是所有的選項配置,我們在項目中不需要每一個都自己設置,一般使用createDefault()創建的ImageLoaderConfiguration就能使用,然後調用ImageLoader的init()方法將ImageLoaderConfiguration參數傳遞進去,ImageLoader使用單例模式。


配置Android 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>  
<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="MyApplication">
        ...
    </application>
</manifest>

接下來我們就可以來加載圖片了,首先我們定義好Activity的佈局文件

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="fill_parent"  
  4.     android:layout_height="fill_parent">  
  5.   
  6.     <ImageView  
  7.         android:layout_gravity="center"  
  8.         android:id="@+id/image"  
  9.         android:src="@drawable/ic_empty"  
  10.         android:layout_width="wrap_content"  
  11.         android:layout_height="wrap_content" />  
  12.   
  13. </FrameLayout>  
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <ImageView
        android:layout_gravity="center"
        android:id="@+id/image"
        android:src="@drawable/ic_empty"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</FrameLayout>

裏面只有一個ImageView,很簡單,接下來我們就去加載圖片,我們會發現ImageLader提供了幾個圖片加載的方法,主要是這幾個displayImage(), loadImage(),loadImageSync(),loadImageSync()方法是同步的,android4.0有個特性,網絡操作不能在主線程,所以loadImageSync()方法我們就不去使用

.

loadimage()加載圖片


我們先使用ImageLoader的loadImage()方法來加載網絡圖片

  1. final ImageView mImageView = (ImageView) findViewById(R.id.image);  
  2.         String imageUrl = "https://lh6.googleusercontent.com/-55osAWw3x0Q/URquUtcFr5I/AAAAAAAAAbs/rWlj1RUKrYI/s1024/A%252520Photographer.jpg";  
  3.           
  4.         ImageLoader.getInstance().loadImage(imageUrl, new ImageLoadingListener() {  
  5.               
  6.             @Override  
  7.             public void onLoadingStarted(String imageUri, View view) {  
  8.                   
  9.             }  
  10.               
  11.             @Override  
  12.             public void onLoadingFailed(String imageUri, View view,  
  13.                     FailReason failReason) {  
  14.                   
  15.             }  
  16.               
  17.             @Override  
  18.             public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {  
  19.                 mImageView.setImageBitmap(loadedImage);  
  20.             }  
  21.               
  22.             @Override  
  23.             public void onLoadingCancelled(String imageUri, View view) {  
  24.                   
  25.             }  
  26.         });  
final ImageView mImageView = (ImageView) findViewById(R.id.image);
		String imageUrl = "https://lh6.googleusercontent.com/-55osAWw3x0Q/URquUtcFr5I/AAAAAAAAAbs/rWlj1RUKrYI/s1024/A%252520Photographer.jpg";
		
		ImageLoader.getInstance().loadImage(imageUrl, new ImageLoadingListener() {
			
			@Override
			public void onLoadingStarted(String imageUri, View view) {
				
			}
			
			@Override
			public void onLoadingFailed(String imageUri, View view,
					FailReason failReason) {
				
			}
			
			@Override
			public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
				mImageView.setImageBitmap(loadedImage);
			}
			
			@Override
			public void onLoadingCancelled(String imageUri, View view) {
				
			}
		});
傳入圖片的url和ImageLoaderListener, 在回調方法onLoadingComplete()中將loadedImage設置到ImageView上面就行了,如果你覺得傳入ImageLoaderListener太複雜了,我們可以使用SimpleImageLoadingListener類,該類提供了ImageLoaderListener接口方法的空實現,使用的是缺省適配器模式

  1. final ImageView mImageView = (ImageView) findViewById(R.id.image);  
  2.         String imageUrl = "https://lh6.googleusercontent.com/-55osAWw3x0Q/URquUtcFr5I/AAAAAAAAAbs/rWlj1RUKrYI/s1024/A%252520Photographer.jpg";  
  3.           
  4.         ImageLoader.getInstance().loadImage(imageUrl, new SimpleImageLoadingListener(){  
  5.   
  6.             @Override  
  7.             public void onLoadingComplete(String imageUri, View view,  
  8.                     Bitmap loadedImage) {  
  9.                 super.onLoadingComplete(imageUri, view, loadedImage);  
  10.                 mImageView.setImageBitmap(loadedImage);  
  11.             }  
  12.               
  13.         });  
final ImageView mImageView = (ImageView) findViewById(R.id.image);
		String imageUrl = "https://lh6.googleusercontent.com/-55osAWw3x0Q/URquUtcFr5I/AAAAAAAAAbs/rWlj1RUKrYI/s1024/A%252520Photographer.jpg";
		
		ImageLoader.getInstance().loadImage(imageUrl, new SimpleImageLoadingListener(){

			@Override
			public void onLoadingComplete(String imageUri, View view,
					Bitmap loadedImage) {
				super.onLoadingComplete(imageUri, view, loadedImage);
				mImageView.setImageBitmap(loadedImage);
			}
			
		});
如果我們要指定圖片的大小該怎麼辦呢,這也好辦,初始化一個ImageSize對象,指定圖片的寬和高,代碼如下

  1. final ImageView mImageView = (ImageView) findViewById(R.id.image);  
  2.         String imageUrl = "https://lh6.googleusercontent.com/-55osAWw3x0Q/URquUtcFr5I/AAAAAAAAAbs/rWlj1RUKrYI/s1024/A%252520Photographer.jpg";  
  3.           
  4.         ImageSize mImageSize = new ImageSize(100100);  
  5.           
  6.         ImageLoader.getInstance().loadImage(imageUrl, mImageSize, new SimpleImageLoadingListener(){  
  7.   
  8.             @Override  
  9.             public void onLoadingComplete(String imageUri, View view,  
  10.                     Bitmap loadedImage) {  
  11.                 super.onLoadingComplete(imageUri, view, loadedImage);  
  12.                 mImageView.setImageBitmap(loadedImage);  
  13.             }  
  14.               
  15.         });  
final ImageView mImageView = (ImageView) findViewById(R.id.image);
		String imageUrl = "https://lh6.googleusercontent.com/-55osAWw3x0Q/URquUtcFr5I/AAAAAAAAAbs/rWlj1RUKrYI/s1024/A%252520Photographer.jpg";
		
		ImageSize mImageSize = new ImageSize(100, 100);
		
		ImageLoader.getInstance().loadImage(imageUrl, mImageSize, new SimpleImageLoadingListener(){

			@Override
			public void onLoadingComplete(String imageUri, View view,
					Bitmap loadedImage) {
				super.onLoadingComplete(imageUri, view, loadedImage);
				mImageView.setImageBitmap(loadedImage);
			}
			
		});

上面只是很簡單的使用ImageLoader來加載網絡圖片,在實際的開發中,我們並不會這麼使用,那我們平常會怎麼使用呢?我們會用到DisplayImageOptions,他可以配置一些圖片顯示的選項,比如圖片在加載中ImageView顯示的圖片,是否需要使用內存緩存,是否需要使用文件緩存等等,可供我們選擇的配置如下

  1. DisplayImageOptions options = new DisplayImageOptions.Builder()  
  2.         .showImageOnLoading(R.drawable.ic_stub) // resource or drawable  
  3.         .showImageForEmptyUri(R.drawable.ic_empty) // resource or drawable  
  4.         .showImageOnFail(R.drawable.ic_error) // resource or drawable  
  5.         .resetViewBeforeLoading(false)  // default  
  6.         .delayBeforeLoading(1000)  
  7.         .cacheInMemory(false// default  
  8.         .cacheOnDisk(false// default  
  9.         .preProcessor(...)  
  10.         .postProcessor(...)  
  11.         .extraForDownloader(...)  
  12.         .considerExifParams(false// default  
  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();  
DisplayImageOptions options = new DisplayImageOptions.Builder()
        .showImageOnLoading(R.drawable.ic_stub) // resource or drawable
        .showImageForEmptyUri(R.drawable.ic_empty) // resource or drawable
        .showImageOnFail(R.drawable.ic_error) // resource or drawable
        .resetViewBeforeLoading(false)  // default
        .delayBeforeLoading(1000)
        .cacheInMemory(false) // default
        .cacheOnDisk(false) // default
        .preProcessor(...)
        .postProcessor(...)
        .extraForDownloader(...)
        .considerExifParams(false) // default
        .imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2) // default
        .bitmapConfig(Bitmap.Config.ARGB_8888) // default
        .decodingOptions(...)
        .displayer(new SimpleBitmapDisplayer()) // default
        .handler(new Handler()) // default
        .build();

我們將上面的代碼稍微修改下

  1. final ImageView mImageView = (ImageView) findViewById(R.id.image);  
  2.         String imageUrl = "https://lh6.googleusercontent.com/-55osAWw3x0Q/URquUtcFr5I/AAAAAAAAAbs/rWlj1RUKrYI/s1024/A%252520Photographer.jpg";  
  3.         ImageSize mImageSize = new ImageSize(100100);  
  4.           
  5.         //顯示圖片的配置  
  6.         DisplayImageOptions options = new DisplayImageOptions.Builder()  
  7.                 .cacheInMemory(true)  
  8.                 .cacheOnDisk(true)  
  9.                 .bitmapConfig(Bitmap.Config.RGB_565)  
  10.                 .build();  
  11.           
  12.         ImageLoader.getInstance().loadImage(imageUrl, mImageSize, options, new SimpleImageLoadingListener(){  
  13.   
  14.             @Override  
  15.             public void onLoadingComplete(String imageUri, View view,  
  16.                     Bitmap loadedImage) {  
  17.                 super.onLoadingComplete(imageUri, view, loadedImage);  
  18.                 mImageView.setImageBitmap(loadedImage);  
  19.             }  
  20.               
  21.         });  
final ImageView mImageView = (ImageView) findViewById(R.id.image);
		String imageUrl = "https://lh6.googleusercontent.com/-55osAWw3x0Q/URquUtcFr5I/AAAAAAAAAbs/rWlj1RUKrYI/s1024/A%252520Photographer.jpg";
		ImageSize mImageSize = new ImageSize(100, 100);
		
		//顯示圖片的配置
		DisplayImageOptions options = new DisplayImageOptions.Builder()
				.cacheInMemory(true)
				.cacheOnDisk(true)
				.bitmapConfig(Bitmap.Config.RGB_565)
				.build();
		
		ImageLoader.getInstance().loadImage(imageUrl, mImageSize, options, new SimpleImageLoadingListener(){

			@Override
			public void onLoadingComplete(String imageUri, View view,
					Bitmap loadedImage) {
				super.onLoadingComplete(imageUri, view, loadedImage);
				mImageView.setImageBitmap(loadedImage);
			}
			
		});

我們使用了DisplayImageOptions來配置顯示圖片的一些選項,這裏我添加了將圖片緩存到內存中已經緩存圖片到文件系統中,這樣我們就不用擔心每次都從網絡中去加載圖片了,是不是很方便呢,但是DisplayImageOptions選項中有些選項對於loadImage()方法是無效的,比如showImageOnLoading, showImageForEmptyUri等,


displayImage()加載圖片


接下來我們就來看看網絡圖片加載的另一個方法displayImage(),代碼如下

  1. final ImageView mImageView = (ImageView) findViewById(R.id.image);  
  2.         String imageUrl = "https://lh6.googleusercontent.com/-55osAWw3x0Q/URquUtcFr5I/AAAAAAAAAbs/rWlj1RUKrYI/s1024/A%252520Photographer.jpg";  
  3.           
  4.         //顯示圖片的配置  
  5.         DisplayImageOptions options = new DisplayImageOptions.Builder()  
  6.                 .showImageOnLoading(R.drawable.ic_stub)  
  7.                 .showImageOnFail(R.drawable.ic_error)  
  8.                 .cacheInMemory(true)  
  9.                 .cacheOnDisk(true)  
  10.                 .bitmapConfig(Bitmap.Config.RGB_565)  
  11.                 .build();  
  12.           
  13.         ImageLoader.getInstance().displayImage(imageUrl, mImageView, options);  
final ImageView mImageView = (ImageView) findViewById(R.id.image);
		String imageUrl = "https://lh6.googleusercontent.com/-55osAWw3x0Q/URquUtcFr5I/AAAAAAAAAbs/rWlj1RUKrYI/s1024/A%252520Photographer.jpg";
		
		//顯示圖片的配置
		DisplayImageOptions options = new DisplayImageOptions.Builder()
				.showImageOnLoading(R.drawable.ic_stub)
				.showImageOnFail(R.drawable.ic_error)
				.cacheInMemory(true)
				.cacheOnDisk(true)
				.bitmapConfig(Bitmap.Config.RGB_565)
				.build();
		
		ImageLoader.getInstance().displayImage(imageUrl, mImageView, options);

從上面的代碼中,我們可以看出,使用displayImage()比使用loadImage()方便很多,也不需要添加ImageLoadingListener接口,我們也不需要手動設置ImageView顯示Bitmap對象,直接將ImageView作爲參數傳遞到displayImage()中就行了,圖片顯示的配置選項中,我們添加了一個圖片加載中ImageVIew上面顯示的圖片,以及圖片加載出現錯誤顯示的圖片,效果如下,剛開始顯示ic_stub圖片,如果圖片加載成功顯示圖片,加載產生錯誤顯示ic_error



這個方法使用起來比較方便,而且使用displayImage()方法 他會根據控件的大小和imageScaleType來自動裁剪圖片,我們修改下MyApplication,開啓Log打印

  1. public class MyApplication extends Application {  
  2.   
  3.     @Override  
  4.     public void onCreate() {  
  5.         super.onCreate();  
  6.   
  7.         //創建默認的ImageLoader配置參數  
  8.         ImageLoaderConfiguration configuration = new ImageLoaderConfiguration.Builder(this)  
  9.         .writeDebugLogs() //打印log信息  
  10.         .build();  
  11.           
  12.           
  13.         //Initialize ImageLoader with configuration.  
  14.         ImageLoader.getInstance().init(configuration);  
  15.     }  
  16.   
  17. }  
public class MyApplication extends Application {

	@Override
	public void onCreate() {
		super.onCreate();

		//創建默認的ImageLoader配置參數
		ImageLoaderConfiguration configuration = new ImageLoaderConfiguration.Builder(this)
		.writeDebugLogs() //打印log信息
		.build();
		
		
		//Initialize ImageLoader with configuration.
		ImageLoader.getInstance().init(configuration);
	}

}

我們來看下圖片加載的Log信息


第一條信息中,告訴我們開始加載圖片,打印出圖片的url以及圖片的最大寬度和高度,圖片的寬高默認是設備的寬高,當然如果我們很清楚圖片的大小,我們也可以去設置這個大小,在ImageLoaderConfiguration的選項中memoryCacheExtraOptions(int maxImageWidthForMemoryCache, int maxImageHeightForMemoryCache)

第二條信息顯示我們加載的圖片來源於網絡

第三條信息顯示圖片的原始大小爲1024 x 682 經過裁剪變成了512 x 341 

第四條顯示圖片加入到了內存緩存中,我這裏沒有加入到sd卡中,所以沒有加入文件緩存的Log


我們在加載網絡圖片的時候,經常有需要顯示圖片下載進度的需求,Universal-Image-Loader當然也提供這樣的功能,只需要在displayImage()方法中傳入ImageLoadingProgressListener接口就行了,代碼如下

  1. imageLoader.displayImage(imageUrl, mImageView, options, new SimpleImageLoadingListener(), new ImageLoadingProgressListener() {  
  2.               
  3.             @Override  
  4.             public void onProgressUpdate(String imageUri, View view, int current,  
  5.                     int total) {  
  6.                   
  7.             }  
  8.         });  
imageLoader.displayImage(imageUrl, mImageView, options, new SimpleImageLoadingListener(), new ImageLoadingProgressListener() {
			
			@Override
			public void onProgressUpdate(String imageUri, View view, int current,
					int total) {
				
			}
		});
由於displayImage()方法中帶ImageLoadingProgressListener參數的方法都有帶ImageLoadingListener參數,所以我這裏直接new 一個SimpleImageLoadingListener,然後我們就可以在回調方法onProgressUpdate()得到圖片的加載進度。


加載其他來源的圖片


使用Universal-Image-Loader框架不僅可以加載網絡圖片,還可以加載sd卡中的圖片,Content provider等,使用也很簡單,只是將圖片的url稍加的改變下就行了,下面是加載文件系統的圖片

  1. //顯示圖片的配置  
  2.         DisplayImageOptions options = new DisplayImageOptions.Builder()  
  3.                 .showImageOnLoading(R.drawable.ic_stub)  
  4.                 .showImageOnFail(R.drawable.ic_error)  
  5.                 .cacheInMemory(true)  
  6.                 .cacheOnDisk(true)  
  7.                 .bitmapConfig(Bitmap.Config.RGB_565)  
  8.                 .build();  
  9.           
  10.         final ImageView mImageView = (ImageView) findViewById(R.id.image);  
  11.         String imagePath = "/mnt/sdcard/image.png";  
  12.         String imageUrl = Scheme.FILE.wrap(imagePath);  
  13.           
  14. //      String imageUrl = "https://img-my.csdn.net/uploads/201309/01/1378037235_7476.jpg";  
  15.           
  16.         imageLoader.displayImage(imageUrl, mImageView, options);  
//顯示圖片的配置
		DisplayImageOptions options = new DisplayImageOptions.Builder()
				.showImageOnLoading(R.drawable.ic_stub)
				.showImageOnFail(R.drawable.ic_error)
				.cacheInMemory(true)
				.cacheOnDisk(true)
				.bitmapConfig(Bitmap.Config.RGB_565)
				.build();
		
		final ImageView mImageView = (ImageView) findViewById(R.id.image);
		String imagePath = "/mnt/sdcard/image.png";
		String imageUrl = Scheme.FILE.wrap(imagePath);
		
//		String imageUrl = "https://img-my.csdn.net/uploads/201309/01/1378037235_7476.jpg";
		
		imageLoader.displayImage(imageUrl, mImageView, options);
當然還有來源於Content provider,drawable,assets中,使用的時候也很簡單,我們只需要給每個圖片來源的地方加上Scheme包裹起來(Content provider除外),然後當做圖片的url傳遞到imageLoader中,Universal-Image-Loader框架會根據不同的Scheme獲取到輸入流

  1. //圖片來源於Content provider  
  2.         String contentprividerUrl = "content://media/external/audio/albumart/13";  
  3.           
  4.         //圖片來源於assets  
  5.         String assetsUrl = Scheme.ASSETS.wrap("image.png");  
  6.           
  7.         //圖片來源於  
  8.         String drawableUrl = Scheme.DRAWABLE.wrap("R.drawable.image");  
//圖片來源於Content provider
		String contentprividerUrl = "content://media/external/audio/albumart/13";
		
		//圖片來源於assets
		String assetsUrl = Scheme.ASSETS.wrap("image.png");
		
		//圖片來源於
		String drawableUrl = Scheme.DRAWABLE.wrap("R.drawable.image");


GirdView,ListView加載圖片


相信大部分人都是使用GridView,ListView來顯示大量的圖片,而當我們快速滑動GridView,ListView,我們希望能停止圖片的加載,而在GridView,ListView停止滑動的時候加載當前界面的圖片,這個框架當然也提供這個功能,使用起來也很簡單,它提供了PauseOnScrollListener這個類來控制ListView,GridView滑動過程中停止去加載圖片,該類使用的是代理模式

  1. listView.setOnScrollListener(new PauseOnScrollListener(imageLoader, pauseOnScroll, pauseOnFling));  
  2.         gridView.setOnScrollListener(new PauseOnScrollListener(imageLoader, pauseOnScroll, pauseOnFling));  
listView.setOnScrollListener(new PauseOnScrollListener(imageLoader, pauseOnScroll, pauseOnFling));
		gridView.setOnScrollListener(new PauseOnScrollListener(imageLoader, pauseOnScroll, pauseOnFling));
第一個參數就是我們的圖片加載對象ImageLoader, 第二個是控制是否在滑動過程中暫停加載圖片,如果需要暫停傳true就行了,第三個參數控制猛的滑動界面的時候圖片是否加載


OutOfMemoryError


雖然這個框架有很好的緩存機制,有效的避免了OOM的產生,一般的情況下產生OOM的概率比較小,但是並不能保證OutOfMemoryError永遠不發生,這個框架對於OutOfMemoryError做了簡單的catch,保證我們的程序遇到OOM而不被crash掉,但是如果我們使用該框架經常發生OOM,我們應該怎麼去改善呢?

  • 減少線程池中線程的個數,在ImageLoaderConfiguration中的(.threadPoolSize)中配置,推薦配置1-5
  • 在DisplayImageOptions選項中配置bitmapConfig爲Bitmap.Config.RGB_565,因爲默認是ARGB_8888, 使用RGB_565會比使用ARGB_8888少消耗2倍的內存
  • 在ImageLoaderConfiguration中配置圖片的內存緩存爲memoryCache(new WeakMemoryCache()) 或者不使用內存緩存
  • 在DisplayImageOptions選項中設置.imageScaleType(ImageScaleType.IN_SAMPLE_INT)或者imageScaleType(ImageScaleType.EXACTLY)

通過上面這些,相信大家對Universal-Image-Loader框架的使用已經非常的瞭解了,我們在使用該框架的時候儘量的使用displayImage()方法去加載圖片,loadImage()是將圖片對象回調到ImageLoadingListener接口的onLoadingComplete()方法中,需要我們手動去設置到ImageView上面,displayImage()方法中,對ImageView對象使用的是Weak references,方便垃圾回收器回收ImageView對象,如果我們要加載固定大小的圖片的時候,使用loadImage()方法需要傳遞一個ImageSize對象,而displayImage()方法會根據ImageView對象的測量值,或者android:layout_width and android:layout_height設定的值,或者android:maxWidth and/or android:maxHeight設定的值來裁剪圖片



=========================================策略部分================================================================================



本篇文章繼續爲大家介紹Universal-Image-Loader這個開源的圖片加載框架,介紹的是圖片緩存策略方面的,如果大家對這個開源框架的使用還不瞭解,大家可以看看我之前寫的一篇文章Android 開源框架Universal-Image-Loader完全解析(一)--- 基本介紹及使用,我們一般去加載大量的圖片的時候,都會做緩存策略,緩存又分爲內存緩存和硬盤緩存,我之前也寫了幾篇異步加載大量圖片的文章,使用的內存緩存是LruCache這個類,LRU是Least Recently Used 近期最少使用算法,我們可以給LruCache設定一個緩存圖片的最大值,它會自動幫我們管理好緩存的圖片總大小是否超過我們設定的值, 超過就刪除近期最少使用的圖片,而作爲一個強大的圖片加載框架,Universal-Image-Loader自然也提供了多種圖片的緩存策略,下面就來詳細的介紹下


內存緩存


首先我們來了解下什麼是強引用和什麼是弱引用?

強引用是指創建一個對象並把這個對象賦給一個引用變量, 強引用有引用變量指向時永遠不會被垃圾回收。即使內存不足的時候寧願報OOM也不被垃圾回收器回收,我們new的對象都是強引用

弱引用通過weakReference類來實現,它具有很強的不確定性,如果垃圾回收器掃描到有着WeakReference的對象,就會將其回收釋放內存


現在我們來看Universal-Image-Loader有哪些內存緩存策略

1. 只使用的是強引用緩存 

  • LruMemoryCache(這個類就是這個開源框架默認的內存緩存類,緩存的是bitmap的強引用,下面我會從源碼上面分析這個類)

2.使用強引用和弱引用相結合的緩存有

  • UsingFreqLimitedMemoryCache(如果緩存的圖片總量超過限定值,先刪除使用頻率最小的bitmap)
  • LRULimitedMemoryCache(這個也是使用的lru算法,和LruMemoryCache不同的是,他緩存的是bitmap的弱引用)
  • FIFOLimitedMemoryCache(先進先出的緩存策略,當超過設定值,先刪除最先加入緩存的bitmap)
  • LargestLimitedMemoryCache(當超過緩存限定值,先刪除最大的bitmap對象)
  • LimitedAgeMemoryCache(當 bitmap加入緩存中的時間超過我們設定的值,將其刪除)

3.只使用弱引用緩存

  • WeakMemoryCache(這個類緩存bitmap的總大小沒有限制,唯一不足的地方就是不穩定,緩存的圖片容易被回收掉)

上面介紹了Universal-Image-Loader所提供的所有的內存緩存的類,當然我們也可以使用我們自己寫的內存緩存類,我們還要看看要怎麼將這些內存緩存加入到我們的項目中,我們只需要配置ImageLoaderConfiguration.memoryCache(...),如下

  1. ImageLoaderConfiguration configuration = new ImageLoaderConfiguration.Builder(this)  
  2.         .memoryCache(new WeakMemoryCache())  
  3.         .build();  
ImageLoaderConfiguration configuration = new ImageLoaderConfiguration.Builder(this)
		.memoryCache(new WeakMemoryCache())
		.build();


下面我們來分析LruMemoryCache這個類的源代碼

  1. package com.nostra13.universalimageloader.cache.memory.impl;  
  2.   
  3. import android.graphics.Bitmap;  
  4. import com.nostra13.universalimageloader.cache.memory.MemoryCacheAware;  
  5.   
  6. import java.util.Collection;  
  7. import java.util.HashSet;  
  8. import java.util.LinkedHashMap;  
  9. import java.util.Map;  
  10.   
  11. /** 
  12.  * A cache that holds strong references to a limited number of Bitmaps. Each time a Bitmap is accessed, it is moved to 
  13.  * the head of a queue. When a Bitmap is added to a full cache, the Bitmap at the end of that queue is evicted and may 
  14.  * become eligible for garbage collection.<br /> 
  15.  * <br /> 
  16.  * <b>NOTE:</b> This cache uses only strong references for stored Bitmaps. 
  17.  * 
  18.  * @author Sergey Tarasevich (nostra13[at]gmail[dot]com) 
  19.  * @since 1.8.1 
  20.  */  
  21. public class LruMemoryCache implements MemoryCacheAware<String, Bitmap> {  
  22.   
  23.     private final LinkedHashMap<String, Bitmap> map;  
  24.   
  25.     private final int maxSize;  
  26.     /** Size of this cache in bytes */  
  27.     private int size;  
  28.   
  29.     /** @param maxSize Maximum sum of the sizes of the Bitmaps in this cache */  
  30.     public LruMemoryCache(int maxSize) {  
  31.         if (maxSize <= 0) {  
  32.             throw new IllegalArgumentException("maxSize <= 0");  
  33.         }  
  34.         this.maxSize = maxSize;  
  35.         this.map = new LinkedHashMap<String, Bitmap>(00.75f, true);  
  36.     }  
  37.   
  38.     /** 
  39.      * Returns the Bitmap for {@code key} if it exists in the cache. If a Bitmap was returned, it is moved to the head 
  40.      * of the queue. This returns null if a Bitmap is not cached. 
  41.      */  
  42.     @Override  
  43.     public final Bitmap get(String key) {  
  44.         if (key == null) {  
  45.             throw new NullPointerException("key == null");  
  46.         }  
  47.   
  48.         synchronized (this) {  
  49.             return map.get(key);  
  50.         }  
  51.     }  
  52.   
  53.     /** Caches {@code Bitmap} for {@code key}. The Bitmap is moved to the head of the queue. */  
  54.     @Override  
  55.     public final boolean put(String key, Bitmap value) {  
  56.         if (key == null || value == null) {  
  57.             throw new NullPointerException("key == null || value == null");  
  58.         }  
  59.   
  60.         synchronized (this) {  
  61.             size += sizeOf(key, value);  
  62.             Bitmap previous = map.put(key, value);  
  63.             if (previous != null) {  
  64.                 size -= sizeOf(key, previous);  
  65.             }  
  66.         }  
  67.   
  68.         trimToSize(maxSize);  
  69.         return true;  
  70.     }  
  71.   
  72.     /** 
  73.      * Remove the eldest entries until the total of remaining entries is at or below the requested size. 
  74.      * 
  75.      * @param maxSize the maximum size of the cache before returning. May be -1 to evict even 0-sized elements. 
  76.      */  
  77.     private void trimToSize(int maxSize) {  
  78.         while (true) {  
  79.             String key;  
  80.             Bitmap value;  
  81.             synchronized (this) {  
  82.                 if (size < 0 || (map.isEmpty() && size != 0)) {  
  83.                     throw new IllegalStateException(getClass().getName() + ".sizeOf() is reporting inconsistent results!");  
  84.                 }  
  85.   
  86.                 if (size <= maxSize || map.isEmpty()) {  
  87.                     break;  
  88.                 }  
  89.   
  90.                 Map.Entry<String, Bitmap> toEvict = map.entrySet().iterator().next();  
  91.                 if (toEvict == null) {  
  92.                     break;  
  93.                 }  
  94.                 key = toEvict.getKey();  
  95.                 value = toEvict.getValue();  
  96.                 map.remove(key);  
  97.                 size -= sizeOf(key, value);  
  98.             }  
  99.         }  
  100.     }  
  101.   
  102.     /** Removes the entry for {@code key} if it exists. */  
  103.     @Override  
  104.     public final void remove(String key) {  
  105.         if (key == null) {  
  106.             throw new NullPointerException("key == null");  
  107.         }  
  108.   
  109.         synchronized (this) {  
  110.             Bitmap previous = map.remove(key);  
  111.             if (previous != null) {  
  112.                 size -= sizeOf(key, previous);  
  113.             }  
  114.         }  
  115.     }  
  116.   
  117.     @Override  
  118.     public Collection<String> keys() {  
  119.         synchronized (this) {  
  120.             return new HashSet<String>(map.keySet());  
  121.         }  
  122.     }  
  123.   
  124.     @Override  
  125.     public void clear() {  
  126.         trimToSize(-1); // -1 will evict 0-sized elements  
  127.     }  
  128.   
  129.     /** 
  130.      * Returns the size {@code Bitmap} in bytes. 
  131.      * <p/> 
  132.      * An entry's size must not change while it is in the cache. 
  133.      */  
  134.     private int sizeOf(String key, Bitmap value) {  
  135.         return value.getRowBytes() * value.getHeight();  
  136.     }  
  137.   
  138.     @Override  
  139.     public synchronized final String toString() {  
  140.         return String.format("LruCache[maxSize=%d]", maxSize);  
  141.     }  
  142. }  
package com.nostra13.universalimageloader.cache.memory.impl;

import android.graphics.Bitmap;
import com.nostra13.universalimageloader.cache.memory.MemoryCacheAware;

import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * A cache that holds strong references to a limited number of Bitmaps. Each time a Bitmap is accessed, it is moved to
 * the head of a queue. When a Bitmap is added to a full cache, the Bitmap at the end of that queue is evicted and may
 * become eligible for garbage collection.<br />
 * <br />
 * <b>NOTE:</b> This cache uses only strong references for stored Bitmaps.
 *
 * @author Sergey Tarasevich (nostra13[at]gmail[dot]com)
 * @since 1.8.1
 */
public class LruMemoryCache implements MemoryCacheAware<String, Bitmap> {

	private final LinkedHashMap<String, Bitmap> map;

	private final int maxSize;
	/** Size of this cache in bytes */
	private int size;

	/** @param maxSize Maximum sum of the sizes of the Bitmaps in this cache */
	public LruMemoryCache(int maxSize) {
		if (maxSize <= 0) {
			throw new IllegalArgumentException("maxSize <= 0");
		}
		this.maxSize = maxSize;
		this.map = new LinkedHashMap<String, Bitmap>(0, 0.75f, true);
	}

	/**
	 * Returns the Bitmap for {@code key} if it exists in the cache. If a Bitmap was returned, it is moved to the head
	 * of the queue. This returns null if a Bitmap is not cached.
	 */
	@Override
	public final Bitmap get(String key) {
		if (key == null) {
			throw new NullPointerException("key == null");
		}

		synchronized (this) {
			return map.get(key);
		}
	}

	/** Caches {@code Bitmap} for {@code key}. The Bitmap is moved to the head of the queue. */
	@Override
	public final boolean put(String key, Bitmap value) {
		if (key == null || value == null) {
			throw new NullPointerException("key == null || value == null");
		}

		synchronized (this) {
			size += sizeOf(key, value);
			Bitmap previous = map.put(key, value);
			if (previous != null) {
				size -= sizeOf(key, previous);
			}
		}

		trimToSize(maxSize);
		return true;
	}

	/**
	 * Remove the eldest entries until the total of remaining entries is at or below the requested size.
	 *
	 * @param maxSize the maximum size of the cache before returning. May be -1 to evict even 0-sized elements.
	 */
	private void trimToSize(int maxSize) {
		while (true) {
			String key;
			Bitmap value;
			synchronized (this) {
				if (size < 0 || (map.isEmpty() && size != 0)) {
					throw new IllegalStateException(getClass().getName() + ".sizeOf() is reporting inconsistent results!");
				}

				if (size <= maxSize || map.isEmpty()) {
					break;
				}

				Map.Entry<String, Bitmap> toEvict = map.entrySet().iterator().next();
				if (toEvict == null) {
					break;
				}
				key = toEvict.getKey();
				value = toEvict.getValue();
				map.remove(key);
				size -= sizeOf(key, value);
			}
		}
	}

	/** Removes the entry for {@code key} if it exists. */
	@Override
	public final void remove(String key) {
		if (key == null) {
			throw new NullPointerException("key == null");
		}

		synchronized (this) {
			Bitmap previous = map.remove(key);
			if (previous != null) {
				size -= sizeOf(key, previous);
			}
		}
	}

	@Override
	public Collection<String> keys() {
		synchronized (this) {
			return new HashSet<String>(map.keySet());
		}
	}

	@Override
	public void clear() {
		trimToSize(-1); // -1 will evict 0-sized elements
	}

	/**
	 * Returns the size {@code Bitmap} in bytes.
	 * <p/>
	 * An entry's size must not change while it is in the cache.
	 */
	private int sizeOf(String key, Bitmap value) {
		return value.getRowBytes() * value.getHeight();
	}

	@Override
	public synchronized final String toString() {
		return String.format("LruCache[maxSize=%d]", maxSize);
	}
}

我們可以看到這個類中維護的是一個LinkedHashMap,在LruMemoryCache構造函數中我們可以看到,我們爲其設置了一個緩存圖片的最大值maxSize,並實例化LinkedHashMap, 而從LinkedHashMap構造函數的第三個參數爲ture,表示它是按照訪問順序進行排序的,
我們來看將bitmap加入到LruMemoryCache的方法put(String key, Bitmap value),  第61行,sizeOf()是計算每張圖片所佔的byte數,size是記錄當前緩存bitmap的總大小,如果該key之前就緩存了bitmap,我們需要將之前的bitmap減掉去,接下來看trimToSize()方法,我們直接看86行,如果當前緩存的bitmap總數小於設定值maxSize,不做任何處理,如果當前緩存的bitmap總數大於maxSize,刪除LinkedHashMap中的第一個元素,size中減去該bitmap對應的byte數

我們可以看到該緩存類比較簡單,邏輯也比較清晰,如果大家想知道其他內存緩存的邏輯,可以去分析分析其源碼,在這裏我簡單說下FIFOLimitedMemoryCache的實現邏輯,該類使用的HashMap來緩存bitmap的弱引用,然後使用LinkedList來保存成功加入到FIFOLimitedMemoryCache的bitmap的強引用,如果加入的FIFOLimitedMemoryCache的bitmap總數超過限定值,直接刪除LinkedList的第一個元素,所以就實現了先進先出的緩存策略,其他的緩存都類似,有興趣的可以去看看。


硬盤緩存


接下來就給大家分析分析硬盤緩存的策略,這個框架也提供了幾種常見的緩存策略,當然如果你覺得都不符合你的要求,你也可以自己去擴展

  • FileCountLimitedDiscCache(可以設定緩存圖片的個數,當超過設定值,刪除掉最先加入到硬盤的文件)
  • LimitedAgeDiscCache(設定文件存活的最長時間,當超過這個值,就刪除該文件)
  • TotalSizeLimitedDiscCache(設定緩存bitmap的最大值,當超過這個值,刪除最先加入到硬盤的文件)
  • UnlimitedDiscCache(這個緩存類沒有任何的限制)

下面我們就來分析分析TotalSizeLimitedDiscCache的源碼實現

  1. /******************************************************************************* 
  2.  * Copyright 2011-2013 Sergey Tarasevich 
  3.  * 
  4.  * Licensed under the Apache License, Version 2.0 (the "License"); 
  5.  * you may not use this file except in compliance with the License. 
  6.  * You may obtain a copy of the License at 
  7.  * 
  8.  * http://www.apache.org/licenses/LICENSE-2.0 
  9.  * 
  10.  * Unless required by applicable law or agreed to in writing, software 
  11.  * distributed under the License is distributed on an "AS IS" BASIS, 
  12.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
  13.  * See the License for the specific language governing permissions and 
  14.  * limitations under the License. 
  15.  *******************************************************************************/  
  16. package com.nostra13.universalimageloader.cache.disc.impl;  
  17.   
  18. import com.nostra13.universalimageloader.cache.disc.LimitedDiscCache;  
  19. import com.nostra13.universalimageloader.cache.disc.naming.FileNameGenerator;  
  20. import com.nostra13.universalimageloader.core.DefaultConfigurationFactory;  
  21. import com.nostra13.universalimageloader.utils.L;  
  22.   
  23. import java.io.File;  
  24.   
  25. /** 
  26.  * Disc cache limited by total cache size. If cache size exceeds specified limit then file with the most oldest last 
  27.  * usage date will be deleted. 
  28.  * 
  29.  * @author Sergey Tarasevich (nostra13[at]gmail[dot]com) 
  30.  * @see LimitedDiscCache 
  31.  * @since 1.0.0 
  32.  */  
  33. public class TotalSizeLimitedDiscCache extends LimitedDiscCache {  
  34.   
  35.     private static final int MIN_NORMAL_CACHE_SIZE_IN_MB = 2;  
  36.     private static final int MIN_NORMAL_CACHE_SIZE = MIN_NORMAL_CACHE_SIZE_IN_MB * 1024 * 1024;  
  37.   
  38.     /** 
  39.      * @param cacheDir     Directory for file caching. <b>Important:</b> Specify separate folder for cached files. It's 
  40.      *                     needed for right cache limit work. 
  41.      * @param maxCacheSize Maximum cache directory size (in bytes). If cache size exceeds this limit then file with the 
  42.      *                     most oldest last usage date will be deleted. 
  43.      */  
  44.     public TotalSizeLimitedDiscCache(File cacheDir, int maxCacheSize) {  
  45.         this(cacheDir, DefaultConfigurationFactory.createFileNameGenerator(), maxCacheSize);  
  46.     }  
  47.   
  48.     /** 
  49.      * @param cacheDir          Directory for file caching. <b>Important:</b> Specify separate folder for cached files. It's 
  50.      *                          needed for right cache limit work. 
  51.      * @param fileNameGenerator Name generator for cached files 
  52.      * @param maxCacheSize      Maximum cache directory size (in bytes). If cache size exceeds this limit then file with the 
  53.      *                          most oldest last usage date will be deleted. 
  54.      */  
  55.     public TotalSizeLimitedDiscCache(File cacheDir, FileNameGenerator fileNameGenerator, int maxCacheSize) {  
  56.         super(cacheDir, fileNameGenerator, maxCacheSize);  
  57.         if (maxCacheSize < MIN_NORMAL_CACHE_SIZE) {  
  58.             L.w("You set too small disc cache size (less than %1$d Mb)", MIN_NORMAL_CACHE_SIZE_IN_MB);  
  59.         }  
  60.     }  
  61.   
  62.     @Override  
  63.     protected int getSize(File file) {  
  64.         return (int) file.length();  
  65.     }  
  66. }  
/*******************************************************************************
 * Copyright 2011-2013 Sergey Tarasevich
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *******************************************************************************/
package com.nostra13.universalimageloader.cache.disc.impl;

import com.nostra13.universalimageloader.cache.disc.LimitedDiscCache;
import com.nostra13.universalimageloader.cache.disc.naming.FileNameGenerator;
import com.nostra13.universalimageloader.core.DefaultConfigurationFactory;
import com.nostra13.universalimageloader.utils.L;

import java.io.File;

/**
 * Disc cache limited by total cache size. If cache size exceeds specified limit then file with the most oldest last
 * usage date will be deleted.
 *
 * @author Sergey Tarasevich (nostra13[at]gmail[dot]com)
 * @see LimitedDiscCache
 * @since 1.0.0
 */
public class TotalSizeLimitedDiscCache extends LimitedDiscCache {

	private static final int MIN_NORMAL_CACHE_SIZE_IN_MB = 2;
	private static final int MIN_NORMAL_CACHE_SIZE = MIN_NORMAL_CACHE_SIZE_IN_MB * 1024 * 1024;

	/**
	 * @param cacheDir     Directory for file caching. <b>Important:</b> Specify separate folder for cached files. It's
	 *                     needed for right cache limit work.
	 * @param maxCacheSize Maximum cache directory size (in bytes). If cache size exceeds this limit then file with the
	 *                     most oldest last usage date will be deleted.
	 */
	public TotalSizeLimitedDiscCache(File cacheDir, int maxCacheSize) {
		this(cacheDir, DefaultConfigurationFactory.createFileNameGenerator(), maxCacheSize);
	}

	/**
	 * @param cacheDir          Directory for file caching. <b>Important:</b> Specify separate folder for cached files. It's
	 *                          needed for right cache limit work.
	 * @param fileNameGenerator Name generator for cached files
	 * @param maxCacheSize      Maximum cache directory size (in bytes). If cache size exceeds this limit then file with the
	 *                          most oldest last usage date will be deleted.
	 */
	public TotalSizeLimitedDiscCache(File cacheDir, FileNameGenerator fileNameGenerator, int maxCacheSize) {
		super(cacheDir, fileNameGenerator, maxCacheSize);
		if (maxCacheSize < MIN_NORMAL_CACHE_SIZE) {
			L.w("You set too small disc cache size (less than %1$d Mb)", MIN_NORMAL_CACHE_SIZE_IN_MB);
		}
	}

	@Override
	protected int getSize(File file) {
		return (int) file.length();
	}
}

這個類是繼承LimitedDiscCache,除了兩個構造函數之外,還重寫了getSize()方法,返回文件的大小,接下來我們就來看看LimitedDiscCache

  1. /******************************************************************************* 
  2.  * Copyright 2011-2013 Sergey Tarasevich 
  3.  * 
  4.  * Licensed under the Apache License, Version 2.0 (the "License"); 
  5.  * you may not use this file except in compliance with the License. 
  6.  * You may obtain a copy of the License at 
  7.  * 
  8.  * http://www.apache.org/licenses/LICENSE-2.0 
  9.  * 
  10.  * Unless required by applicable law or agreed to in writing, software 
  11.  * distributed under the License is distributed on an "AS IS" BASIS, 
  12.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
  13.  * See the License for the specific language governing permissions and 
  14.  * limitations under the License. 
  15.  *******************************************************************************/  
  16. package com.nostra13.universalimageloader.cache.disc;  
  17.   
  18. import com.nostra13.universalimageloader.cache.disc.naming.FileNameGenerator;  
  19. import com.nostra13.universalimageloader.core.DefaultConfigurationFactory;  
  20.   
  21. import java.io.File;  
  22. import java.util.Collections;  
  23. import java.util.HashMap;  
  24. import java.util.Map;  
  25. import java.util.Map.Entry;  
  26. import java.util.Set;  
  27. import java.util.concurrent.atomic.AtomicInteger;  
  28.   
  29. /** 
  30.  * Abstract disc cache limited by some parameter. If cache exceeds specified limit then file with the most oldest last 
  31.  * usage date will be deleted. 
  32.  * 
  33.  * @author Sergey Tarasevich (nostra13[at]gmail[dot]com) 
  34.  * @see BaseDiscCache 
  35.  * @see FileNameGenerator 
  36.  * @since 1.0.0 
  37.  */  
  38. public abstract class LimitedDiscCache extends BaseDiscCache {  
  39.   
  40.     private static final int INVALID_SIZE = -1;  
  41.   
  42.     //記錄緩存文件的大小  
  43.     private final AtomicInteger cacheSize;  
  44.     //緩存文件的最大值  
  45.     private final int sizeLimit;  
  46.     private final Map<File, Long> lastUsageDates = Collections.synchronizedMap(new HashMap<File, Long>());  
  47.   
  48.     /** 
  49.      * @param cacheDir  Directory for file caching. <b>Important:</b> Specify separate folder for cached files. It's 
  50.      *                  needed for right cache limit work. 
  51.      * @param sizeLimit Cache limit value. If cache exceeds this limit then file with the most oldest last usage date 
  52.      *                  will be deleted. 
  53.      */  
  54.     public LimitedDiscCache(File cacheDir, int sizeLimit) {  
  55.         this(cacheDir, DefaultConfigurationFactory.createFileNameGenerator(), sizeLimit);  
  56.     }  
  57.   
  58.     /** 
  59.      * @param cacheDir          Directory for file caching. <b>Important:</b> Specify separate folder for cached files. It's 
  60.      *                          needed for right cache limit work. 
  61.      * @param fileNameGenerator Name generator for cached files 
  62.      * @param sizeLimit         Cache limit value. If cache exceeds this limit then file with the most oldest last usage date 
  63.      *                          will be deleted. 
  64.      */  
  65.     public LimitedDiscCache(File cacheDir, FileNameGenerator fileNameGenerator, int sizeLimit) {  
  66.         super(cacheDir, fileNameGenerator);  
  67.         this.sizeLimit = sizeLimit;  
  68.         cacheSize = new AtomicInteger();  
  69.         calculateCacheSizeAndFillUsageMap();  
  70.     }  
  71.   
  72.     /** 
  73.      * 另開線程計算cacheDir裏面文件的大小,並將文件和最後修改的毫秒數加入到Map中 
  74.      */  
  75.     private void calculateCacheSizeAndFillUsageMap() {  
  76.         new Thread(new Runnable() {  
  77.             @Override  
  78.             public void run() {  
  79.                 int size = 0;  
  80.                 File[] cachedFiles = cacheDir.listFiles();  
  81.                 if (cachedFiles != null) { // rarely but it can happen, don't know why  
  82.                     for (File cachedFile : cachedFiles) {  
  83.                         //getSize()是一個抽象方法,子類自行實現getSize()的邏輯  
  84.                         size += getSize(cachedFile);  
  85.                         //將文件的最後修改時間加入到map中  
  86.                         lastUsageDates.put(cachedFile, cachedFile.lastModified());  
  87.                     }  
  88.                     cacheSize.set(size);  
  89.                 }  
  90.             }  
  91.         }).start();  
  92.     }  
  93.   
  94.     /** 
  95.      * 將文件添加到Map中,並計算緩存文件的大小是否超過了我們設置的最大緩存數 
  96.      * 超過了就刪除最先加入的那個文件 
  97.      */  
  98.     @Override  
  99.     public void put(String key, File file) {  
  100.         //要加入文件的大小  
  101.         int valueSize = getSize(file);  
  102.           
  103.         //獲取當前緩存文件大小總數  
  104.         int curCacheSize = cacheSize.get();  
  105.         //判斷是否超過設定的最大緩存值  
  106.         while (curCacheSize + valueSize > sizeLimit) {  
  107.             int freedSize = removeNext();  
  108.             if (freedSize == INVALID_SIZE) break// cache is empty (have nothing to delete)  
  109.             curCacheSize = cacheSize.addAndGet(-freedSize);  
  110.         }  
  111.         cacheSize.addAndGet(valueSize);  
  112.   
  113.         Long currentTime = System.currentTimeMillis();  
  114.         file.setLastModified(currentTime);  
  115.         lastUsageDates.put(file, currentTime);  
  116.     }  
  117.   
  118.     /** 
  119.      * 根據key生成文件 
  120.      */  
  121.     @Override  
  122.     public File get(String key) {  
  123.         File file = super.get(key);  
  124.   
  125.         Long currentTime = System.currentTimeMillis();  
  126.         file.setLastModified(currentTime);  
  127.         lastUsageDates.put(file, currentTime);  
  128.   
  129.         return file;  
  130.     }  
  131.   
  132.     /** 
  133.      * 硬盤緩存的清理 
  134.      */  
  135.     @Override  
  136.     public void clear() {  
  137.         lastUsageDates.clear();  
  138.         cacheSize.set(0);  
  139.         super.clear();  
  140.     }  
  141.   
  142.       
  143.     /** 
  144.      * 獲取最早加入的緩存文件,並將其刪除 
  145.      */  
  146.     private int removeNext() {  
  147.         if (lastUsageDates.isEmpty()) {  
  148.             return INVALID_SIZE;  
  149.         }  
  150.         Long oldestUsage = null;  
  151.         File mostLongUsedFile = null;  
  152.           
  153.         Set<Entry<File, Long>> entries = lastUsageDates.entrySet();  
  154.         synchronized (lastUsageDates) {  
  155.             for (Entry<File, Long> entry : entries) {  
  156.                 if (mostLongUsedFile == null) {  
  157.                     mostLongUsedFile = entry.getKey();  
  158.                     oldestUsage = entry.getValue();  
  159.                 } else {  
  160.                     Long lastValueUsage = entry.getValue();  
  161.                     if (lastValueUsage < oldestUsage) {  
  162.                         oldestUsage = lastValueUsage;  
  163.                         mostLongUsedFile = entry.getKey();  
  164.                     }  
  165.                 }  
  166.             }  
  167.         }  
  168.   
  169.         int fileSize = 0;  
  170.         if (mostLongUsedFile != null) {  
  171.             if (mostLongUsedFile.exists()) {  
  172.                 fileSize = getSize(mostLongUsedFile);  
  173.                 if (mostLongUsedFile.delete()) {  
  174.                     lastUsageDates.remove(mostLongUsedFile);  
  175.                 }  
  176.             } else {  
  177.                 lastUsageDates.remove(mostLongUsedFile);  
  178.             }  
  179.         }  
  180.         return fileSize;  
  181.     }  
  182.   
  183.     /** 
  184.      * 抽象方法,獲取文件大小 
  185.      * @param file 
  186.      * @return 
  187.      */  
  188.     protected abstract int getSize(File file);  
  189. }  
/*******************************************************************************
 * Copyright 2011-2013 Sergey Tarasevich
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *******************************************************************************/
package com.nostra13.universalimageloader.cache.disc;

import com.nostra13.universalimageloader.cache.disc.naming.FileNameGenerator;
import com.nostra13.universalimageloader.core.DefaultConfigurationFactory;

import java.io.File;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Abstract disc cache limited by some parameter. If cache exceeds specified limit then file with the most oldest last
 * usage date will be deleted.
 *
 * @author Sergey Tarasevich (nostra13[at]gmail[dot]com)
 * @see BaseDiscCache
 * @see FileNameGenerator
 * @since 1.0.0
 */
public abstract class LimitedDiscCache extends BaseDiscCache {

	private static final int INVALID_SIZE = -1;

	//記錄緩存文件的大小
	private final AtomicInteger cacheSize;
	//緩存文件的最大值
	private final int sizeLimit;
	private final Map<File, Long> lastUsageDates = Collections.synchronizedMap(new HashMap<File, Long>());

	/**
	 * @param cacheDir  Directory for file caching. <b>Important:</b> Specify separate folder for cached files. It's
	 *                  needed for right cache limit work.
	 * @param sizeLimit Cache limit value. If cache exceeds this limit then file with the most oldest last usage date
	 *                  will be deleted.
	 */
	public LimitedDiscCache(File cacheDir, int sizeLimit) {
		this(cacheDir, DefaultConfigurationFactory.createFileNameGenerator(), sizeLimit);
	}

	/**
	 * @param cacheDir          Directory for file caching. <b>Important:</b> Specify separate folder for cached files. It's
	 *                          needed for right cache limit work.
	 * @param fileNameGenerator Name generator for cached files
	 * @param sizeLimit         Cache limit value. If cache exceeds this limit then file with the most oldest last usage date
	 *                          will be deleted.
	 */
	public LimitedDiscCache(File cacheDir, FileNameGenerator fileNameGenerator, int sizeLimit) {
		super(cacheDir, fileNameGenerator);
		this.sizeLimit = sizeLimit;
		cacheSize = new AtomicInteger();
		calculateCacheSizeAndFillUsageMap();
	}

	/**
	 * 另開線程計算cacheDir裏面文件的大小,並將文件和最後修改的毫秒數加入到Map中
	 */
	private void calculateCacheSizeAndFillUsageMap() {
		new Thread(new Runnable() {
			@Override
			public void run() {
				int size = 0;
				File[] cachedFiles = cacheDir.listFiles();
				if (cachedFiles != null) { // rarely but it can happen, don't know why
					for (File cachedFile : cachedFiles) {
						//getSize()是一個抽象方法,子類自行實現getSize()的邏輯
						size += getSize(cachedFile);
						//將文件的最後修改時間加入到map中
						lastUsageDates.put(cachedFile, cachedFile.lastModified());
					}
					cacheSize.set(size);
				}
			}
		}).start();
	}

	/**
	 * 將文件添加到Map中,並計算緩存文件的大小是否超過了我們設置的最大緩存數
	 * 超過了就刪除最先加入的那個文件
	 */
	@Override
	public void put(String key, File file) {
		//要加入文件的大小
		int valueSize = getSize(file);
		
		//獲取當前緩存文件大小總數
		int curCacheSize = cacheSize.get();
		//判斷是否超過設定的最大緩存值
		while (curCacheSize + valueSize > sizeLimit) {
			int freedSize = removeNext();
			if (freedSize == INVALID_SIZE) break; // cache is empty (have nothing to delete)
			curCacheSize = cacheSize.addAndGet(-freedSize);
		}
		cacheSize.addAndGet(valueSize);

		Long currentTime = System.currentTimeMillis();
		file.setLastModified(currentTime);
		lastUsageDates.put(file, currentTime);
	}

	/**
	 * 根據key生成文件
	 */
	@Override
	public File get(String key) {
		File file = super.get(key);

		Long currentTime = System.currentTimeMillis();
		file.setLastModified(currentTime);
		lastUsageDates.put(file, currentTime);

		return file;
	}

	/**
	 * 硬盤緩存的清理
	 */
	@Override
	public void clear() {
		lastUsageDates.clear();
		cacheSize.set(0);
		super.clear();
	}

	
	/**
	 * 獲取最早加入的緩存文件,並將其刪除
	 */
	private int removeNext() {
		if (lastUsageDates.isEmpty()) {
			return INVALID_SIZE;
		}
		Long oldestUsage = null;
		File mostLongUsedFile = null;
		
		Set<Entry<File, Long>> entries = lastUsageDates.entrySet();
		synchronized (lastUsageDates) {
			for (Entry<File, Long> entry : entries) {
				if (mostLongUsedFile == null) {
					mostLongUsedFile = entry.getKey();
					oldestUsage = entry.getValue();
				} else {
					Long lastValueUsage = entry.getValue();
					if (lastValueUsage < oldestUsage) {
						oldestUsage = lastValueUsage;
						mostLongUsedFile = entry.getKey();
					}
				}
			}
		}

		int fileSize = 0;
		if (mostLongUsedFile != null) {
			if (mostLongUsedFile.exists()) {
				fileSize = getSize(mostLongUsedFile);
				if (mostLongUsedFile.delete()) {
					lastUsageDates.remove(mostLongUsedFile);
				}
			} else {
				lastUsageDates.remove(mostLongUsedFile);
			}
		}
		return fileSize;
	}

	/**
	 * 抽象方法,獲取文件大小
	 * @param file
	 * @return
	 */
	protected abstract int getSize(File file);
}

在構造方法中,第69行有一個方法calculateCacheSizeAndFillUsageMap(),該方法是計算cacheDir的文件大小,並將文件和文件的最後修改時間加入到Map中

然後是將文件加入硬盤緩存的方法put(),在106行判斷當前文件的緩存總數加上即將要加入緩存的文件大小是否超過緩存設定值,如果超過了執行removeNext()方法,接下來就來看看這個方法的具體實現,150-167中找出最先加入硬盤的文件,169-180中將其從文件硬盤中刪除,並返回該文件的大小,刪除成功之後成員變量cacheSize需要減掉改文件大小。

FileCountLimitedDiscCache這個類實現邏輯跟TotalSizeLimitedDiscCache是一樣的,區別在於getSize()方法,前者返回1,表示爲文件數是1,後者返回文件的大小。

等我寫完了這篇文章,我才發現FileCountLimitedDiscCache和TotalSizeLimitedDiscCache在最新的源碼中已經刪除了,加入了LruDiscCache,由於我的是之前的源碼,所以我也不改了,大家如果想要了解LruDiscCache可以去看最新的源碼,我這裏就不介紹了,還好內存緩存的沒變化,下面分析的是最新的源碼中的部分,我們在使用中可以不自行配置硬盤緩存策略,直接用DefaultConfigurationFactory中的就行了

我們看DefaultConfigurationFactory這個類的createDiskCache()方法

  1. /** 
  2.  * Creates default implementation of {@link DiskCache} depends on incoming parameters 
  3.  */  
  4. public static DiskCache createDiskCache(Context context, FileNameGenerator diskCacheFileNameGenerator,  
  5.         long diskCacheSize, int diskCacheFileCount) {  
  6.     File reserveCacheDir = createReserveDiskCacheDir(context);  
  7.     if (diskCacheSize > 0 || diskCacheFileCount > 0) {  
  8.         File individualCacheDir = StorageUtils.getIndividualCacheDirectory(context);  
  9.         LruDiscCache diskCache = new LruDiscCache(individualCacheDir, diskCacheFileNameGenerator, diskCacheSize,  
  10.                 diskCacheFileCount);  
  11.         diskCache.setReserveCacheDir(reserveCacheDir);  
  12.         return diskCache;  
  13.     } else {  
  14.         File cacheDir = StorageUtils.getCacheDirectory(context);  
  15.         return new UnlimitedDiscCache(cacheDir, reserveCacheDir, diskCacheFileNameGenerator);  
  16.     }  
  17. }  
	/**
	 * Creates default implementation of {@link DiskCache} depends on incoming parameters
	 */
	public static DiskCache createDiskCache(Context context, FileNameGenerator diskCacheFileNameGenerator,
			long diskCacheSize, int diskCacheFileCount) {
		File reserveCacheDir = createReserveDiskCacheDir(context);
		if (diskCacheSize > 0 || diskCacheFileCount > 0) {
			File individualCacheDir = StorageUtils.getIndividualCacheDirectory(context);
			LruDiscCache diskCache = new LruDiscCache(individualCacheDir, diskCacheFileNameGenerator, diskCacheSize,
					diskCacheFileCount);
			diskCache.setReserveCacheDir(reserveCacheDir);
			return diskCache;
		} else {
			File cacheDir = StorageUtils.getCacheDirectory(context);
			return new UnlimitedDiscCache(cacheDir, reserveCacheDir, diskCacheFileNameGenerator);
		}
	}

如果我們在ImageLoaderConfiguration中配置了diskCacheSize和diskCacheFileCount,他就使用的是LruDiscCache,否則使用的是UnlimitedDiscCache,在最新的源碼中還有一個硬盤緩存類可以配置,那就是LimitedAgeDiscCache,可以在ImageLoaderConfiguration.diskCache(...)配置




-=====================================源碼部分===================================================================

本篇文章主要是帶大家從源碼的角度上面去解讀這個強大的圖片加載框架,自己很久沒有寫文章了,感覺生疏了許多,距離上一篇文章三個月多了,確實是自己平常忙,換了工作很多東西都要去看去理解,然後加上自己也懶了,沒有以前那麼有激情了,我感覺這節奏不對,我要繼續保持以前的激情,正所謂好記性不如爛筆頭,有時候自己也會去翻看下之前寫的東西,我覺得知識寫下來比在腦海中留存的更久,今天就給大家來讀一讀這個框架的源碼,我感覺這個圖片加載框架確實寫的很不錯,讀完代碼自己也學到了很多我希望大家可以堅持看完,看完了對你絕對是有收穫的。

  1. ImageView mImageView = (ImageView) findViewById(R.id.image);    
  2.         String imageUrl = "https://lh6.googleusercontent.com/-55osAWw3x0Q/URquUtcFr5I/AAAAAAAAAbs/rWlj1RUKrYI/s1024/A%252520Photographer.jpg";    
  3.             
  4.         //顯示圖片的配置    
  5.         DisplayImageOptions options = new DisplayImageOptions.Builder()    
  6.                 .showImageOnLoading(R.drawable.ic_stub)    
  7.                 .showImageOnFail(R.drawable.ic_error)    
  8.                 .cacheInMemory(true)    
  9.                 .cacheOnDisk(true)    
  10.                 .bitmapConfig(Bitmap.Config.RGB_565)    
  11.                 .build();    
  12.             
  13.         ImageLoader.getInstance().displayImage(imageUrl, mImageView, options);    
ImageView mImageView = (ImageView) findViewById(R.id.image);  
        String imageUrl = "https://lh6.googleusercontent.com/-55osAWw3x0Q/URquUtcFr5I/AAAAAAAAAbs/rWlj1RUKrYI/s1024/A%252520Photographer.jpg";  
          
        //顯示圖片的配置  
        DisplayImageOptions options = new DisplayImageOptions.Builder()  
                .showImageOnLoading(R.drawable.ic_stub)  
                .showImageOnFail(R.drawable.ic_error)  
                .cacheInMemory(true)  
                .cacheOnDisk(true)  
                .bitmapConfig(Bitmap.Config.RGB_565)  
                .build();  
          
        ImageLoader.getInstance().displayImage(imageUrl, mImageView, options);  

大部分的時候我們都是使用上面的代碼去加載圖片,我們先看下

  1. public void displayImage(String uri, ImageView imageView, DisplayImageOptions options) {  
  2.         displayImage(uri, new ImageViewAware(imageView), options, nullnull);  
  3.     }  
public void displayImage(String uri, ImageView imageView, DisplayImageOptions options) {
		displayImage(uri, new ImageViewAware(imageView), options, null, null);
	}

從上面的代碼中,我們可以看出,它會將ImageView轉換成ImageViewAware, ImageViewAware主要是做什麼的呢?該類主要是將ImageView進行一個包裝,將ImageView的強引用變成弱引用,當內存不足的時候,可以更好的回收ImageView對象,還有就是獲取ImageView的寬度和高度。這使得我們可以根據ImageView的寬高去對圖片進行一個裁剪,減少內存的使用。

接下來看具體的displayImage方法啦,由於這個方法代碼量蠻多的,所以這裏我分開來讀

  1. checkConfiguration();  
  2.         if (imageAware == null) {  
  3.             throw new IllegalArgumentException(ERROR_WRONG_ARGUMENTS);  
  4.         }  
  5.         if (listener == null) {  
  6.             listener = emptyListener;  
  7.         }  
  8.         if (options == null) {  
  9.             options = configuration.defaultDisplayImageOptions;  
  10.         }  
  11.   
  12.         if (TextUtils.isEmpty(uri)) {  
  13.             engine.cancelDisplayTaskFor(imageAware);  
  14.             listener.onLoadingStarted(uri, imageAware.getWrappedView());  
  15.             if (options.shouldShowImageForEmptyUri()) {  
  16.                 imageAware.setImageDrawable(options.getImageForEmptyUri(configuration.resources));  
  17.             } else {  
  18.                 imageAware.setImageDrawable(null);  
  19.             }  
  20.             listener.onLoadingComplete(uri, imageAware.getWrappedView(), null);  
  21.             return;  
  22.         }  
checkConfiguration();
		if (imageAware == null) {
			throw new IllegalArgumentException(ERROR_WRONG_ARGUMENTS);
		}
		if (listener == null) {
			listener = emptyListener;
		}
		if (options == null) {
			options = configuration.defaultDisplayImageOptions;
		}

		if (TextUtils.isEmpty(uri)) {
			engine.cancelDisplayTaskFor(imageAware);
			listener.onLoadingStarted(uri, imageAware.getWrappedView());
			if (options.shouldShowImageForEmptyUri()) {
				imageAware.setImageDrawable(options.getImageForEmptyUri(configuration.resources));
			} else {
				imageAware.setImageDrawable(null);
			}
			listener.onLoadingComplete(uri, imageAware.getWrappedView(), null);
			return;
		}

第1行代碼是檢查ImageLoaderConfiguration是否初始化,這個初始化是在Application中進行的

12-21行主要是針對url爲空的時候做的處理,第13行代碼中,ImageLoaderEngine中存在一個HashMap,用來記錄正在加載的任務,加載圖片的時候會將ImageView的id和圖片的url加上尺寸加入到HashMap中,加載完成之後會將其移除,然後將DisplayImageOptions的imageResForEmptyUri的圖片設置給ImageView,最後回調給ImageLoadingListener接口告訴它這次任務完成了。

  1. ImageSize targetSize = ImageSizeUtils.defineTargetSizeForView(imageAware, configuration.getMaxImageSize());  
  2.     String memoryCacheKey = MemoryCacheUtils.generateKey(uri, targetSize);  
  3.     engine.prepareDisplayTaskFor(imageAware, memoryCacheKey);  
  4.   
  5.     listener.onLoadingStarted(uri, imageAware.getWrappedView());  
  6.   
  7.     Bitmap bmp = configuration.memoryCache.get(memoryCacheKey);  
  8.     if (bmp != null && !bmp.isRecycled()) {  
  9.         L.d(LOG_LOAD_IMAGE_FROM_MEMORY_CACHE, memoryCacheKey);  
  10.   
  11.         if (options.shouldPostProcess()) {  
  12.             ImageLoadingInfo imageLoadingInfo = new ImageLoadingInfo(uri, imageAware, targetSize, memoryCacheKey,  
  13.                     options, listener, progressListener, engine.getLockForUri(uri));  
  14.             ProcessAndDisplayImageTask displayTask = new ProcessAndDisplayImageTask(engine, bmp, imageLoadingInfo,  
  15.                     defineHandler(options));  
  16.             if (options.isSyncLoading()) {  
  17.                 displayTask.run();  
  18.             } else {  
  19.                 engine.submit(displayTask);  
  20.             }  
  21.         } else {  
  22.             options.getDisplayer().display(bmp, imageAware, LoadedFrom.MEMORY_CACHE);  
  23.             listener.onLoadingComplete(uri, imageAware.getWrappedView(), bmp);  
  24.         }  
  25.     }  
	ImageSize targetSize = ImageSizeUtils.defineTargetSizeForView(imageAware, configuration.getMaxImageSize());
		String memoryCacheKey = MemoryCacheUtils.generateKey(uri, targetSize);
		engine.prepareDisplayTaskFor(imageAware, memoryCacheKey);

		listener.onLoadingStarted(uri, imageAware.getWrappedView());

		Bitmap bmp = configuration.memoryCache.get(memoryCacheKey);
		if (bmp != null && !bmp.isRecycled()) {
			L.d(LOG_LOAD_IMAGE_FROM_MEMORY_CACHE, memoryCacheKey);

			if (options.shouldPostProcess()) {
				ImageLoadingInfo imageLoadingInfo = new ImageLoadingInfo(uri, imageAware, targetSize, memoryCacheKey,
						options, listener, progressListener, engine.getLockForUri(uri));
				ProcessAndDisplayImageTask displayTask = new ProcessAndDisplayImageTask(engine, bmp, imageLoadingInfo,
						defineHandler(options));
				if (options.isSyncLoading()) {
					displayTask.run();
				} else {
					engine.submit(displayTask);
				}
			} else {
				options.getDisplayer().display(bmp, imageAware, LoadedFrom.MEMORY_CACHE);
				listener.onLoadingComplete(uri, imageAware.getWrappedView(), bmp);
			}
		}

第1行主要是將ImageView的寬高封裝成ImageSize對象,如果獲取ImageView的寬高爲0,就會使用手機屏幕的寬高作爲ImageView的寬高,我們在使用ListView,GridView去加載圖片的時候,第一頁獲取寬度是0,所以第一頁使用的手機的屏幕寬高,後面的獲取的都是控件本身的大小了

第7行從內存緩存中獲取Bitmap對象,我們可以再ImageLoaderConfiguration中配置內存緩存邏輯,默認使用的是LruMemoryCache,這個類我在前面的文章中講過

第11行中有一個判斷,我們如果在DisplayImageOptions中設置了postProcessor就進入true邏輯,不過默認postProcessor是爲null的,BitmapProcessor接口主要是對Bitmap進行處理,這個框架並沒有給出相對應的實現,如果我們有自己的需求的時候可以自己實現BitmapProcessor接口(比如將圖片設置成圓形的)

第22 -23行是將Bitmap設置到ImageView上面,這裏我們可以在DisplayImageOptions中配置顯示需求displayer,默認使用的是SimpleBitmapDisplayer,直接將Bitmap設置到ImageView上面,我們可以配置其他的顯示邏輯, 他這裏提供了FadeInBitmapDisplayer(透明度從0-1)RoundedBitmapDisplayer(4個角是圓弧)等, 然後回調到ImageLoadingListener接口

  1. if (options.shouldShowImageOnLoading()) {  
  2.                 imageAware.setImageDrawable(options.getImageOnLoading(configuration.resources));  
  3.             } else if (options.isResetViewBeforeLoading()) {  
  4.                 imageAware.setImageDrawable(null);  
  5.             }  
  6.   
  7.             ImageLoadingInfo imageLoadingInfo = new ImageLoadingInfo(uri, imageAware, targetSize, memoryCacheKey,  
  8.                     options, listener, progressListener, engine.getLockForUri(uri));  
  9.             LoadAndDisplayImageTask displayTask = new LoadAndDisplayImageTask(engine, imageLoadingInfo,  
  10.                     defineHandler(options));  
  11.             if (options.isSyncLoading()) {  
  12.                 displayTask.run();  
  13.             } else {  
  14.                 engine.submit(displayTask);  
  15.             }  
if (options.shouldShowImageOnLoading()) {
				imageAware.setImageDrawable(options.getImageOnLoading(configuration.resources));
			} else if (options.isResetViewBeforeLoading()) {
				imageAware.setImageDrawable(null);
			}

			ImageLoadingInfo imageLoadingInfo = new ImageLoadingInfo(uri, imageAware, targetSize, memoryCacheKey,
					options, listener, progressListener, engine.getLockForUri(uri));
			LoadAndDisplayImageTask displayTask = new LoadAndDisplayImageTask(engine, imageLoadingInfo,
					defineHandler(options));
			if (options.isSyncLoading()) {
				displayTask.run();
			} else {
				engine.submit(displayTask);
			}

這段代碼主要是Bitmap不在內存緩存,從文件中或者網絡裏面獲取bitmap對象,實例化一個LoadAndDisplayImageTask對象,LoadAndDisplayImageTask實現了Runnable,如果配置了isSyncLoading爲true, 直接執行LoadAndDisplayImageTask的run方法,表示同步,默認是false,將LoadAndDisplayImageTask提交給線程池對象

接下來我們就看LoadAndDisplayImageTask的run(), 這個類還是蠻複雜的,我們還是一段一段的分析

  1. if (waitIfPaused()) return;  
  2. if (delayIfNeed()) return;  
if (waitIfPaused()) return;
if (delayIfNeed()) return;

如果waitIfPaused(), delayIfNeed()返回true的話,直接從run()方法中返回了,不執行下面的邏輯, 接下來我們先看看waitIfPaused()

  1. private boolean waitIfPaused() {  
  2.     AtomicBoolean pause = engine.getPause();  
  3.     if (pause.get()) {  
  4.         synchronized (engine.getPauseLock()) {  
  5.             if (pause.get()) {  
  6.                 L.d(LOG_WAITING_FOR_RESUME, memoryCacheKey);  
  7.                 try {  
  8.                     engine.getPauseLock().wait();  
  9.                 } catch (InterruptedException e) {  
  10.                     L.e(LOG_TASK_INTERRUPTED, memoryCacheKey);  
  11.                     return true;  
  12.                 }  
  13.                 L.d(LOG_RESUME_AFTER_PAUSE, memoryCacheKey);  
  14.             }  
  15.         }  
  16.     }  
  17.     return isTaskNotActual();  
  18. }  
	private boolean waitIfPaused() {
		AtomicBoolean pause = engine.getPause();
		if (pause.get()) {
			synchronized (engine.getPauseLock()) {
				if (pause.get()) {
					L.d(LOG_WAITING_FOR_RESUME, memoryCacheKey);
					try {
						engine.getPauseLock().wait();
					} catch (InterruptedException e) {
						L.e(LOG_TASK_INTERRUPTED, memoryCacheKey);
						return true;
					}
					L.d(LOG_RESUME_AFTER_PAUSE, memoryCacheKey);
				}
			}
		}
		return isTaskNotActual();
	}

這個方法是幹嘛用呢,主要是我們在使用ListView,GridView去加載圖片的時候,有時候爲了滑動更加的流暢,我們會選擇手指在滑動或者猛地一滑動的時候不去加載圖片,所以才提出了這麼一個方法,那麼要怎麼用呢?  這裏用到了PauseOnScrollListener這個類,使用很簡單ListView.setOnScrollListener(new PauseOnScrollListener(pauseOnScroll, pauseOnFling )), pauseOnScroll控制我們緩慢滑動ListView,GridView是否停止加載圖片,pauseOnFling 控制猛的滑動ListView,GridView是否停止加載圖片

除此之外,這個方法的返回值由isTaskNotActual()決定,我們接着看看isTaskNotActual()的源碼

  1. private boolean isTaskNotActual() {  
  2.         return isViewCollected() || isViewReused();  
  3.     }  
private boolean isTaskNotActual() {
		return isViewCollected() || isViewReused();
	}

isViewCollected()是判斷我們ImageView是否被垃圾回收器回收了,如果回收了,LoadAndDisplayImageTask方法的run()就直接返回了,isViewReused()判斷該ImageView是否被重用,被重用run()方法也直接返回,爲什麼要用isViewReused()方法呢?主要是ListView,GridView我們會複用item對象,假如我們先去加載ListView,GridView第一頁的圖片的時候,第一頁圖片還沒有全部加載完我們就快速的滾動,isViewReused()方法就會避免這些不可見的item去加載圖片,而直接加載當前界面的圖片

  1. ReentrantLock loadFromUriLock = imageLoadingInfo.loadFromUriLock;  
  2.         L.d(LOG_START_DISPLAY_IMAGE_TASK, memoryCacheKey);  
  3.         if (loadFromUriLock.isLocked()) {  
  4.             L.d(LOG_WAITING_FOR_IMAGE_LOADED, memoryCacheKey);  
  5.         }  
  6.   
  7.         loadFromUriLock.lock();  
  8.         Bitmap bmp;  
  9.         try {  
  10.             checkTaskNotActual();  
  11.   
  12.             bmp = configuration.memoryCache.get(memoryCacheKey);  
  13.             if (bmp == null || bmp.isRecycled()) {  
  14.                 bmp = tryLoadBitmap();  
  15.                 if (bmp == nullreturn// listener callback already was fired  
  16.   
  17.                 checkTaskNotActual();  
  18.                 checkTaskInterrupted();  
  19.   
  20.                 if (options.shouldPreProcess()) {  
  21.                     L.d(LOG_PREPROCESS_IMAGE, memoryCacheKey);  
  22.                     bmp = options.getPreProcessor().process(bmp);  
  23.                     if (bmp == null) {  
  24.                         L.e(ERROR_PRE_PROCESSOR_NULL, memoryCacheKey);  
  25.                     }  
  26.                 }  
  27.   
  28.                 if (bmp != null && options.isCacheInMemory()) {  
  29.                     L.d(LOG_CACHE_IMAGE_IN_MEMORY, memoryCacheKey);  
  30.                     configuration.memoryCache.put(memoryCacheKey, bmp);  
  31.                 }  
  32.             } else {  
  33.                 loadedFrom = LoadedFrom.MEMORY_CACHE;  
  34.                 L.d(LOG_GET_IMAGE_FROM_MEMORY_CACHE_AFTER_WAITING, memoryCacheKey);  
  35.             }  
  36.   
  37.             if (bmp != null && options.shouldPostProcess()) {  
  38.                 L.d(LOG_POSTPROCESS_IMAGE, memoryCacheKey);  
  39.                 bmp = options.getPostProcessor().process(bmp);  
  40.                 if (bmp == null) {  
  41.                     L.e(ERROR_POST_PROCESSOR_NULL, memoryCacheKey);  
  42.                 }  
  43.             }  
  44.             checkTaskNotActual();  
  45.             checkTaskInterrupted();  
  46.         } catch (TaskCancelledException e) {  
  47.             fireCancelEvent();  
  48.             return;  
  49.         } finally {  
  50.             loadFromUriLock.unlock();  
  51.         }  
ReentrantLock loadFromUriLock = imageLoadingInfo.loadFromUriLock;
		L.d(LOG_START_DISPLAY_IMAGE_TASK, memoryCacheKey);
		if (loadFromUriLock.isLocked()) {
			L.d(LOG_WAITING_FOR_IMAGE_LOADED, memoryCacheKey);
		}

		loadFromUriLock.lock();
		Bitmap bmp;
		try {
			checkTaskNotActual();

			bmp = configuration.memoryCache.get(memoryCacheKey);
			if (bmp == null || bmp.isRecycled()) {
				bmp = tryLoadBitmap();
				if (bmp == null) return; // listener callback already was fired

				checkTaskNotActual();
				checkTaskInterrupted();

				if (options.shouldPreProcess()) {
					L.d(LOG_PREPROCESS_IMAGE, memoryCacheKey);
					bmp = options.getPreProcessor().process(bmp);
					if (bmp == null) {
						L.e(ERROR_PRE_PROCESSOR_NULL, memoryCacheKey);
					}
				}

				if (bmp != null && options.isCacheInMemory()) {
					L.d(LOG_CACHE_IMAGE_IN_MEMORY, memoryCacheKey);
					configuration.memoryCache.put(memoryCacheKey, bmp);
				}
			} else {
				loadedFrom = LoadedFrom.MEMORY_CACHE;
				L.d(LOG_GET_IMAGE_FROM_MEMORY_CACHE_AFTER_WAITING, memoryCacheKey);
			}

			if (bmp != null && options.shouldPostProcess()) {
				L.d(LOG_POSTPROCESS_IMAGE, memoryCacheKey);
				bmp = options.getPostProcessor().process(bmp);
				if (bmp == null) {
					L.e(ERROR_POST_PROCESSOR_NULL, memoryCacheKey);
				}
			}
			checkTaskNotActual();
			checkTaskInterrupted();
		} catch (TaskCancelledException e) {
			fireCancelEvent();
			return;
		} finally {
			loadFromUriLock.unlock();
		}

第1行代碼有一個loadFromUriLock,這個是一個鎖,獲取鎖的方法在ImageLoaderEngine類的getLockForUri()方法中

  1. ReentrantLock getLockForUri(String uri) {  
  2.         ReentrantLock lock = uriLocks.get(uri);  
  3.         if (lock == null) {  
  4.             lock = new ReentrantLock();  
  5.             uriLocks.put(uri, lock);  
  6.         }  
  7.         return lock;  
  8.     }  
ReentrantLock getLockForUri(String uri) {
		ReentrantLock lock = uriLocks.get(uri);
		if (lock == null) {
			lock = new ReentrantLock();
			uriLocks.put(uri, lock);
		}
		return lock;
	}

從上面可以看出,這個鎖對象與圖片的url是相互對應的,爲什麼要這麼做?也行你還有點不理解,不知道大家有沒有考慮過一個場景,假如在一個ListView中,某個item正在獲取圖片的過程中,而此時我們將這個item滾出界面之後又將其滾進來,滾進來之後如果沒有加鎖,該item又會去加載一次圖片,假設在很短的時間內滾動很頻繁,那麼就會出現多次去網絡上面請求圖片,所以這裏根據圖片的Url去對應一個ReentrantLock對象,讓具有相同Url的請求就會在第7行等待,等到這次圖片加載完成之後,ReentrantLock就被釋放,剛剛那些相同Url的請求就會繼續執行第7行下面的代碼

來到第12行,它們會先從內存緩存中獲取一遍,如果內存緩存中沒有在去執行下面的邏輯,所以ReentrantLock的作用就是避免這種情況下重複的去從網絡上面請求圖片。

第14行的方法tryLoadBitmap(),這個方法確實也有點長,我先告訴大家,這裏面的邏輯是先從文件緩存中獲取有沒有Bitmap對象,如果沒有在去從網絡中獲取,然後將bitmap保存在文件系統中,我們還是具體分析下

  1. File imageFile = configuration.diskCache.get(uri);  
  2.             if (imageFile != null && imageFile.exists()) {  
  3.                 L.d(LOG_LOAD_IMAGE_FROM_DISK_CACHE, memoryCacheKey);  
  4.                 loadedFrom = LoadedFrom.DISC_CACHE;  
  5.   
  6.                 checkTaskNotActual();  
  7.                 bitmap = decodeImage(Scheme.FILE.wrap(imageFile.getAbsolutePath()));  
  8.             }  
File imageFile = configuration.diskCache.get(uri);
			if (imageFile != null && imageFile.exists()) {
				L.d(LOG_LOAD_IMAGE_FROM_DISK_CACHE, memoryCacheKey);
				loadedFrom = LoadedFrom.DISC_CACHE;

				checkTaskNotActual();
				bitmap = decodeImage(Scheme.FILE.wrap(imageFile.getAbsolutePath()));
			}

先判斷文件緩存中有沒有該文件,如果有的話,直接去調用decodeImage()方法去解碼圖片,該方法裏面調用BaseImageDecoder類的decode()方法,根據ImageView的寬高,ScaleType去裁剪圖片,具體的代碼我就不介紹了,大家自己去看看,我們接下往下看tryLoadBitmap()方法

  1. if (bitmap == null || bitmap.getWidth() <= 0 || bitmap.getHeight() <= 0) {  
  2.             L.d(LOG_LOAD_IMAGE_FROM_NETWORK, memoryCacheKey);  
  3.             loadedFrom = LoadedFrom.NETWORK;  
  4.   
  5.             String imageUriForDecoding = uri;  
  6.             if (options.isCacheOnDisk() && tryCacheImageOnDisk()) {  
  7.                 imageFile = configuration.diskCache.get(uri);  
  8.                 if (imageFile != null) {  
  9.                     imageUriForDecoding = Scheme.FILE.wrap(imageFile.getAbsolutePath());  
  10.                 }  
  11.             }  
  12.   
  13.             checkTaskNotActual();  
  14.             bitmap = decodeImage(imageUriForDecoding);  
  15.   
  16.             if (bitmap == null || bitmap.getWidth() <= 0 || bitmap.getHeight() <= 0) {  
  17.                 fireFailEvent(FailType.DECODING_ERROR, null);  
  18.             }  
  19.         }  
	if (bitmap == null || bitmap.getWidth() <= 0 || bitmap.getHeight() <= 0) {
				L.d(LOG_LOAD_IMAGE_FROM_NETWORK, memoryCacheKey);
				loadedFrom = LoadedFrom.NETWORK;

				String imageUriForDecoding = uri;
				if (options.isCacheOnDisk() && tryCacheImageOnDisk()) {
					imageFile = configuration.diskCache.get(uri);
					if (imageFile != null) {
						imageUriForDecoding = Scheme.FILE.wrap(imageFile.getAbsolutePath());
					}
				}

				checkTaskNotActual();
				bitmap = decodeImage(imageUriForDecoding);

				if (bitmap == null || bitmap.getWidth() <= 0 || bitmap.getHeight() <= 0) {
					fireFailEvent(FailType.DECODING_ERROR, null);
				}
			}

第1行表示從文件緩存中獲取的Bitmap爲null,或者寬高爲0,就去網絡上面獲取Bitmap,來到第6行代碼是否配置了DisplayImageOptions的isCacheOnDisk,表示是否需要將Bitmap對象保存在文件系統中,一般我們需要配置爲true, 默認是false這個要注意下,然後就是執行tryCacheImageOnDisk()方法,去服務器上面拉取圖片並保存在本地文件中

  1. private Bitmap decodeImage(String imageUri) throws IOException {  
  2.     ViewScaleType viewScaleType = imageAware.getScaleType();  
  3.     ImageDecodingInfo decodingInfo = new ImageDecodingInfo(memoryCacheKey, imageUri, uri, targetSize, viewScaleType,  
  4.             getDownloader(), options);  
  5.     return decoder.decode(decodingInfo);  
  6. }  
  7.   
  8. /** @return <b>true</b> - if image was downloaded successfully; <b>false</b> - otherwise */  
  9. private boolean tryCacheImageOnDisk() throws TaskCancelledException {  
  10.     L.d(LOG_CACHE_IMAGE_ON_DISK, memoryCacheKey);  
  11.   
  12.     boolean loaded;  
  13.     try {  
  14.         loaded = downloadImage();  
  15.         if (loaded) {  
  16.             int width = configuration.maxImageWidthForDiskCache;  
  17.             int height = configuration.maxImageHeightForDiskCache;  
  18.               
  19.             if (width > 0 || height > 0) {  
  20.                 L.d(LOG_RESIZE_CACHED_IMAGE_FILE, memoryCacheKey);  
  21.                 resizeAndSaveImage(width, height); // TODO : process boolean result  
  22.             }  
  23.         }  
  24.     } catch (IOException e) {  
  25.         L.e(e);  
  26.         loaded = false;  
  27.     }  
  28.     return loaded;  
  29. }  
  30.   
  31. private boolean downloadImage() throws IOException {  
  32.     InputStream is = getDownloader().getStream(uri, options.getExtraForDownloader());  
  33.     return configuration.diskCache.save(uri, is, this);  
  34. }  
	private Bitmap decodeImage(String imageUri) throws IOException {
		ViewScaleType viewScaleType = imageAware.getScaleType();
		ImageDecodingInfo decodingInfo = new ImageDecodingInfo(memoryCacheKey, imageUri, uri, targetSize, viewScaleType,
				getDownloader(), options);
		return decoder.decode(decodingInfo);
	}

	/** @return <b>true</b> - if image was downloaded successfully; <b>false</b> - otherwise */
	private boolean tryCacheImageOnDisk() throws TaskCancelledException {
		L.d(LOG_CACHE_IMAGE_ON_DISK, memoryCacheKey);

		boolean loaded;
		try {
			loaded = downloadImage();
			if (loaded) {
				int width = configuration.maxImageWidthForDiskCache;
				int height = configuration.maxImageHeightForDiskCache;
				
				if (width > 0 || height > 0) {
					L.d(LOG_RESIZE_CACHED_IMAGE_FILE, memoryCacheKey);
					resizeAndSaveImage(width, height); // TODO : process boolean result
				}
			}
		} catch (IOException e) {
			L.e(e);
			loaded = false;
		}
		return loaded;
	}

	private boolean downloadImage() throws IOException {
		InputStream is = getDownloader().getStream(uri, options.getExtraForDownloader());
		return configuration.diskCache.save(uri, is, this);
	}

第6行的downloadImage()方法是負責下載圖片,並將其保持到文件緩存中,將下載保存Bitmap的進度回調到IoUtils.CopyListener接口的onBytesCopied(int current, int total)方法中,所以我們可以設置ImageLoadingProgressListener接口來獲取圖片下載保存的進度,這裏保存在文件系統中的圖片是原圖

第16-17行,獲取ImageLoaderConfiguration是否設置保存在文件系統中的圖片大小,如果設置了maxImageWidthForDiskCache和maxImageHeightForDiskCache,會調用resizeAndSaveImage()方法對圖片進行裁剪然後在替換之前的原圖,保存裁剪後的圖片到文件系統的,之前有同學問過我說這個框架保存在文件系統的圖片都是原圖,怎麼才能保存縮略圖,只要在Application中實例化ImageLoaderConfiguration的時候設置maxImageWidthForDiskCache和maxImageHeightForDiskCache就行了

  1. if (bmp == nullreturn// listener callback already was fired  
  2.   
  3.                 checkTaskNotActual();  
  4.                 checkTaskInterrupted();  
  5.   
  6.                 if (options.shouldPreProcess()) {  
  7.                     L.d(LOG_PREPROCESS_IMAGE, memoryCacheKey);  
  8.                     bmp = options.getPreProcessor().process(bmp);  
  9.                     if (bmp == null) {  
  10.                         L.e(ERROR_PRE_PROCESSOR_NULL, memoryCacheKey);  
  11.                     }  
  12.                 }  
  13.   
  14.                 if (bmp != null && options.isCacheInMemory()) {  
  15.                     L.d(LOG_CACHE_IMAGE_IN_MEMORY, memoryCacheKey);  
  16.                     configuration.memoryCache.put(memoryCacheKey, bmp);  
  17.                 }  
if (bmp == null) return; // listener callback already was fired

				checkTaskNotActual();
				checkTaskInterrupted();

				if (options.shouldPreProcess()) {
					L.d(LOG_PREPROCESS_IMAGE, memoryCacheKey);
					bmp = options.getPreProcessor().process(bmp);
					if (bmp == null) {
						L.e(ERROR_PRE_PROCESSOR_NULL, memoryCacheKey);
					}
				}

				if (bmp != null && options.isCacheInMemory()) {
					L.d(LOG_CACHE_IMAGE_IN_MEMORY, memoryCacheKey);
					configuration.memoryCache.put(memoryCacheKey, bmp);
				}

接下來這裏就簡單了,6-12行是否要對Bitmap進行處理,這個需要自行實現,14-17就是將圖片保存到內存緩存中去

  1. DisplayBitmapTask displayBitmapTask = new DisplayBitmapTask(bmp, imageLoadingInfo, engine, loadedFrom);  
  2.         runTask(displayBitmapTask, syncLoading, handler, engine);  
DisplayBitmapTask displayBitmapTask = new DisplayBitmapTask(bmp, imageLoadingInfo, engine, loadedFrom);
		runTask(displayBitmapTask, syncLoading, handler, engine);

最後這兩行代碼就是一個顯示任務,直接看DisplayBitmapTask類的run()方法

  1. @Override  
  2.     public void run() {  
  3.         if (imageAware.isCollected()) {  
  4.             L.d(LOG_TASK_CANCELLED_IMAGEAWARE_COLLECTED, memoryCacheKey);  
  5.             listener.onLoadingCancelled(imageUri, imageAware.getWrappedView());  
  6.         } else if (isViewWasReused()) {  
  7.             L.d(LOG_TASK_CANCELLED_IMAGEAWARE_REUSED, memoryCacheKey);  
  8.             listener.onLoadingCancelled(imageUri, imageAware.getWrappedView());  
  9.         } else {  
  10.             L.d(LOG_DISPLAY_IMAGE_IN_IMAGEAWARE, loadedFrom, memoryCacheKey);  
  11.             displayer.display(bitmap, imageAware, loadedFrom);  
  12.             engine.cancelDisplayTaskFor(imageAware);  
  13.             listener.onLoadingComplete(imageUri, imageAware.getWrappedView(), bitmap);  
  14.         }  
  15.     }  
@Override
	public void run() {
		if (imageAware.isCollected()) {
			L.d(LOG_TASK_CANCELLED_IMAGEAWARE_COLLECTED, memoryCacheKey);
			listener.onLoadingCancelled(imageUri, imageAware.getWrappedView());
		} else if (isViewWasReused()) {
			L.d(LOG_TASK_CANCELLED_IMAGEAWARE_REUSED, memoryCacheKey);
			listener.onLoadingCancelled(imageUri, imageAware.getWrappedView());
		} else {
			L.d(LOG_DISPLAY_IMAGE_IN_IMAGEAWARE, loadedFrom, memoryCacheKey);
			displayer.display(bitmap, imageAware, loadedFrom);
			engine.cancelDisplayTaskFor(imageAware);
			listener.onLoadingComplete(imageUri, imageAware.getWrappedView(), bitmap);
		}
	}

假如ImageView被回收了或者被重用了,回調給ImageLoadingListener接口,否則就調用BitmapDisplayer去顯示Bitmap



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