欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

全面解析Android的開源圖片框架Universal-Image-Loader

 更新時間:2016年04月01日 15:10:36   作者:xiaanming  
這篇文章主要介紹了Android的開源圖片框架Universal-Image-Loader,Universal-Image-Loader在GitHub上開源,其提供的圖片加載功能令人印象相當(dāng)深刻,需要的朋友可以參考下

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

  • 多線程下載圖片,圖片可以來源于網(wǎng)絡(luò),文件系統(tǒng),項目文件夾assets中以及drawable中等
  • 支持隨意的配置ImageLoader,例如線程池,圖片下載器,內(nèi)存緩存策略,硬盤緩存策略,圖片顯示選項以及其他的一些配置
  • 支持圖片的內(nèi)存緩存,文件系統(tǒng)緩存或者SD卡緩存
  • 支持圖片下載過程的監(jiān)聽
  • 根據(jù)控件(ImageView)的大小對Bitmap進(jìn)行裁剪,減少Bitmap占用過多的內(nèi)存
  • 較好的控制圖片的加載過程,例如暫停圖片加載,重新開始加載圖片,一般使用在ListView,GridView中
  • 動過程中暫停加載圖片
  • 停止滑動的時候去加載圖片
  • 供在較慢的網(wǎng)絡(luò)下對圖片進(jìn)行加載。

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

新建一個Android項目,下載JAR包添加到工程libs目錄下。
新建一個MyApplication繼承Application,并在onCreate()中創(chuàng)建ImageLoader的配置參數(shù),并初始化到ImageLoader中代碼如下:

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(); 
 
  //創(chuàng)建默認(rèn)的ImageLoader配置參數(shù) 
  ImageLoaderConfiguration configuration = ImageLoaderConfiguration 
    .createDefault(this); 
   
  //Initialize ImageLoader with configuration. 
  ImageLoader.getInstance().init(configuration); 
 } 
 
} 

ImageLoaderConfiguration是圖片加載器ImageLoader的配置參數(shù),使用了建造者模式,這里是直接使用了createDefault()方法創(chuàng)建一個默認(rèn)的ImageLoaderConfiguration,當(dāng)然我們還可以自己設(shè)置ImageLoaderConfiguration,設(shè)置如下

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(); 

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

配置Android 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的布局文件

<?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,很簡單,接下來我們就去加載圖片,我們會發(fā)現(xiàn)ImageLader提供了幾個圖片加載的方法,主要是這幾個displayImage(), loadImage(),loadImageSync(),loadImageSync()方法是同步的,android4.0有個特性,網(wǎng)絡(luò)操作不能在主線程,所以loadImageSync()方法我們就不去使用
.
loadimage()加載圖片

我們先使用ImageLoader的loadImage()方法來加載網(wǎng)絡(luò)圖片

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, 在回調(diào)方法onLoadingComplete()中將loadedImage設(shè)置到ImageView上面就行了,如果你覺得傳入ImageLoaderListener太復(fù)雜了,我們可以使用SimpleImageLoadingListener類,該類提供了ImageLoaderListener接口方法的空實現(xiàn),使用的是缺省適配器模式

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對象,指定圖片的寬和高,代碼如下

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來加載網(wǎng)絡(luò)圖片,在實際的開發(fā)中,我們并不會這么使用,那我們平常會怎么使用呢?我們會用到DisplayImageOptions,他可以配置一些圖片顯示的選項,比如圖片在加載中ImageView顯示的圖片,是否需要使用內(nèi)存緩存,是否需要使用文件緩存等等,可供我們選擇的配置如下

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(); 

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

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來配置顯示圖片的一些選項,這里我添加了將圖片緩存到內(nèi)存中已經(jīng)緩存圖片到文件系統(tǒng)中,這樣我們就不用擔(dān)心每次都從網(wǎng)絡(luò)中去加載圖片了,是不是很方便呢,但是DisplayImageOptions選項中有些選項對于loadImage()方法是無效的,比如showImageOnLoading, showImageForEmptyUri等,

displayImage()加載圖片

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

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接口,我們也不需要手動設(shè)置ImageView顯示Bitmap對象,直接將ImageView作為參數(shù)傳遞到displayImage()中就行了,圖片顯示的配置選項中,我們添加了一個圖片加載中ImageVIew上面顯示的圖片,以及圖片加載出現(xiàn)錯誤顯示的圖片,效果如下,剛開始顯示ic_stub圖片,如果圖片加載成功顯示圖片,加載產(chǎn)生錯誤顯示ic_error

201641150230560.gif (417×615)201641150258580.gif (417×615)

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

public class MyApplication extends Application { 
 
 @Override 
 public void onCreate() { 
  super.onCreate(); 
 
  //創(chuàng)建默認(rèn)的ImageLoader配置參數(shù) 
  ImageLoaderConfiguration configuration = new ImageLoaderConfiguration.Builder(this) 
  .writeDebugLogs() //打印log信息 
  .build(); 
   
   
  //Initialize ImageLoader with configuration. 
  ImageLoader.getInstance().init(configuration); 
 } 
 
} 

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

201641150445496.jpg (862×288)

第一條信息中,告訴我們開始加載圖片,打印出圖片的url以及圖片的最大寬度和高度,圖片的寬高默認(rèn)是設(shè)備的寬高,當(dāng)然如果我們很清楚圖片的大小,我們也可以去設(shè)置這個大小,在ImageLoaderConfiguration的選項中memoryCacheExtraOptions(int maxImageWidthForMemoryCache, int maxImageHeightForMemoryCache)
第二條信息顯示我們加載的圖片來源于網(wǎng)絡(luò)
第三條信息顯示圖片的原始大小為1024 x 682 經(jīng)過裁剪變成了512 x 341
第四條顯示圖片加入到了內(nèi)存緩存中,我這里沒有加入到sd卡中,所以沒有加入文件緩存的Log

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

imageLoader.displayImage(imageUrl, mImageView, options, new SimpleImageLoadingListener(), new ImageLoadingProgressListener() { 
    
   @Override 
   public void onProgressUpdate(String imageUri, View view, int current, 
     int total) { 
     
   } 
  }); 

由于displayImage()方法中帶ImageLoadingProgressListener參數(shù)的方法都有帶ImageLoadingListener參數(shù),所以我這里直接new 一個SimpleImageLoadingListener,然后我們就可以在回調(diào)方法onProgressUpdate()得到圖片的加載進(jìn)度。

加載其他來源的圖片

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

//顯示圖片的配置 
  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 = "http://img.my.csdn.net/uploads/201309/01/1378037235_7476.jpg"; 
   
  imageLoader.displayImage(imageUrl, mImageView, options); 

當(dāng)然還有來源于Content provider,drawable,assets中,使用的時候也很簡單,我們只需要給每個圖片來源的地方加上Scheme包裹起來(Content provider除外),然后當(dāng)做圖片的url傳遞到imageLoader中,Universal-Image-Loader框架會根據(jù)不同的Scheme獲取到輸入流

//圖片來源于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來顯示大量的圖片,而當(dāng)我們快速滑動GridView,ListView,我們希望能停止圖片的加載,而在GridView,ListView停止滑動的時候加載當(dāng)前界面的圖片,這個框架當(dāng)然也提供這個功能,使用起來也很簡單,它提供了PauseOnScrollListener這個類來控制ListView,GridView滑動過程中停止去加載圖片,該類使用的是代理模式
[java] view plain copy 在CODE上查看代碼片派生到我的代碼片
listView.setOnScrollListener(new PauseOnScrollListener(imageLoader, pauseOnScroll, pauseOnFling)); 
        gridView.setOnScrollListener(new PauseOnScrollListener(imageLoader, pauseOnScroll, pauseOnFling)); 
第一個參數(shù)就是我們的圖片加載對象ImageLoader, 第二個是控制是否在滑動過程中暫停加載圖片,如果需要暫停傳true就行了,第三個參數(shù)控制猛的滑動界面的時候圖片是否加載

OutOfMemoryError

雖然這個框架有很好的緩存機制,有效的避免了OOM的產(chǎn)生,一般的情況下產(chǎn)生OOM的概率比較小,但是并不能保證OutOfMemoryError永遠(yuǎn)不發(fā)生,這個框架對于OutOfMemoryError做了簡單的catch,保證我們的程序遇到OOM而不被crash掉,但是如果我們使用該框架經(jīng)常發(fā)生OOM,我們應(yīng)該怎么去改善呢?
減少線程池中線程的個數(shù),在ImageLoaderConfiguration中的(.threadPoolSize)中配置,推薦配置1-5
在DisplayImageOptions選項中配置bitmapConfig為Bitmap.Config.RGB_565,因為默認(rèn)是ARGB_8888, 使用RGB_565會比使用ARGB_8888少消耗2倍的內(nèi)存
在ImageLoaderConfiguration中配置圖片的內(nèi)存緩存為memoryCache(new WeakMemoryCache()) 或者不使用內(nèi)存緩存
在DisplayImageOptions選項中設(shè)置.imageScaleType(ImageScaleType.IN_SAMPLE_INT)或者imageScaleType(ImageScaleType.EXACTLY)
通過上面這些,相信大家對Universal-Image-Loader框架的使用已經(jīng)非常的了解了,我們在使用該框架的時候盡量的使用displayImage()方法去加載圖片,loadImage()是將圖片對象回調(diào)到ImageLoadingListener接口的onLoadingComplete()方法中,需要我們手動去設(shè)置到ImageView上面,displayImage()方法中,對ImageView對象使用的是Weak references,方便垃圾回收器回收ImageView對象,如果我們要加載固定大小的圖片的時候,使用loadImage()方法需要傳遞一個ImageSize對象,而displayImage()方法會根據(jù)ImageView對象的測量值,或者android:layout_width and android:layout_height設(shè)定的值,或者android:maxWidth and/or android:maxHeight設(shè)定的值來裁剪圖片。

內(nèi)存緩存

首先我們來了解下什么是強引用和什么是弱引用?
強引用是指創(chuàng)建一個對象并把這個對象賦給一個引用變量, 強引用有引用變量指向時永遠(yuǎn)不會被垃圾回收。即使內(nèi)存不足的時候?qū)幵笀驩OM也不被垃圾回收器回收,我們new的對象都是強引用
弱引用通過weakReference類來實現(xiàn),它具有很強的不確定性,如果垃圾回收器掃描到有著WeakReference的對象,就會將其回收釋放內(nèi)存

現(xiàn)在我們來看Universal-Image-Loader有哪些內(nèi)存緩存策略
1. 只使用的是強引用緩存
LruMemoryCache(這個類就是這個開源框架默認(rèn)的內(nèi)存緩存類,緩存的是bitmap的強引用,下面我會從源碼上面分析這個類)
2.使用強引用和弱引用相結(jié)合的緩存有
UsingFreqLimitedMemoryCache(如果緩存的圖片總量超過限定值,先刪除使用頻率最小的bitmap)
LRULimitedMemoryCache(這個也是使用的lru算法,和LruMemoryCache不同的是,他緩存的是bitmap的弱引用)
FIFOLimitedMemoryCache(先進(jìn)先出的緩存策略,當(dāng)超過設(shè)定值,先刪除最先加入緩存的bitmap)
LargestLimitedMemoryCache(當(dāng)超過緩存限定值,先刪除最大的bitmap對象)
LimitedAgeMemoryCache(當(dāng) bitmap加入緩存中的時間超過我們設(shè)定的值,將其刪除)
3.只使用弱引用緩存
WeakMemoryCache(這個類緩存bitmap的總大小沒有限制,唯一不足的地方就是不穩(wěn)定,緩存的圖片容易被回收掉)
上面介紹了Universal-Image-Loader所提供的所有的內(nèi)存緩存的類,當(dāng)然我們也可以使用我們自己寫的內(nèi)存緩存類,我們還要看看要怎么將這些內(nèi)存緩存加入到我們的項目中,我們只需要配置ImageLoaderConfiguration.memoryCache(...),如下

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

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

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); 
 } 
} 

我們可以看到這個類中維護(hù)的是一個LinkedHashMap,在LruMemoryCache構(gòu)造函數(shù)中我們可以看到,我們?yōu)槠湓O(shè)置了一個緩存圖片的最大值maxSize,并實例化LinkedHashMap, 而從LinkedHashMap構(gòu)造函數(shù)的第三個參數(shù)為ture,表示它是按照訪問順序進(jìn)行排序的,
我們來看將bitmap加入到LruMemoryCache的方法put(String key, Bitmap value),  第61行,sizeOf()是計算每張圖片所占的byte數(shù),size是記錄當(dāng)前緩存bitmap的總大小,如果該key之前就緩存了bitmap,我們需要將之前的bitmap減掉去,接下來看trimToSize()方法,我們直接看86行,如果當(dāng)前緩存的bitmap總數(shù)小于設(shè)定值maxSize,不做任何處理,如果當(dāng)前緩存的bitmap總數(shù)大于maxSize,刪除LinkedHashMap中的第一個元素,size中減去該bitmap對應(yīng)的byte數(shù)
我們可以看到該緩存類比較簡單,邏輯也比較清晰,如果大家想知道其他內(nèi)存緩存的邏輯,可以去分析分析其源碼,在這里我簡單說下FIFOLimitedMemoryCache的實現(xiàn)邏輯,該類使用的HashMap來緩存bitmap的弱引用,然后使用LinkedList來保存成功加入到FIFOLimitedMemoryCache的bitmap的強引用,如果加入的FIFOLimitedMemoryCache的bitmap總數(shù)超過限定值,直接刪除LinkedList的第一個元素,所以就實現(xiàn)了先進(jìn)先出的緩存策略,其他的緩存都類似,有興趣的可以去看看。

硬盤緩存

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

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

下面我們就來分析分析TotalSizeLimitedDiscCache的源碼實現(xiàn)

/******************************************************************************* 
 * 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,除了兩個構(gòu)造函數(shù)之外,還重寫了getSize()方法,返回文件的大小,接下來我們就來看看LimitedDiscCache

/******************************************************************************* 
 * 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里面文件的大小,并將文件和最后修改的毫秒數(shù)加入到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()是一個抽象方法,子類自行實現(xiàn)getSize()的邏輯 
      size += getSize(cachedFile); 
      //將文件的最后修改時間加入到map中 
      lastUsageDates.put(cachedFile, cachedFile.lastModified()); 
     } 
     cacheSize.set(size); 
    } 
   } 
  }).start(); 
 } 
 
 /** 
  * 將文件添加到Map中,并計算緩存文件的大小是否超過了我們設(shè)置的最大緩存數(shù) 
  * 超過了就刪除最先加入的那個文件 
  */ 
 @Override 
 public void put(String key, File file) { 
  //要加入文件的大小 
  int valueSize = getSize(file); 
   
  //獲取當(dāng)前緩存文件大小總數(shù) 
  int curCacheSize = cacheSize.get(); 
  //判斷是否超過設(shè)定的最大緩存值 
  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); 
 } 
 
 /** 
  * 根據(jù)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); 
} 

在構(gòu)造方法中,第69行有一個方法calculateCacheSizeAndFillUsageMap(),該方法是計算cacheDir的文件大小,并將文件和文件的最后修改時間加入到Map中
然后是將文件加入硬盤緩存的方法put(),在106行判斷當(dāng)前文件的緩存總數(shù)加上即將要加入緩存的文件大小是否超過緩存設(shè)定值,如果超過了執(zhí)行removeNext()方法,接下來就來看看這個方法的具體實現(xiàn),150-167中找出最先加入硬盤的文件,169-180中將其從文件硬盤中刪除,并返回該文件的大小,刪除成功之后成員變量cacheSize需要減掉改文件大小。
FileCountLimitedDiscCache這個類實現(xiàn)邏輯跟TotalSizeLimitedDiscCache是一樣的,區(qū)別在于getSize()方法,前者返回1,表示為文件數(shù)是1,后者返回文件的大小。
等我寫完了這篇文章,我才發(fā)現(xiàn)FileCountLimitedDiscCache和TotalSizeLimitedDiscCache在最新的源碼中已經(jīng)刪除了,加入了LruDiscCache,由于我的是之前的源碼,所以我也不改了,大家如果想要了解LruDiscCache可以去看最新的源碼,我這里就不介紹了,還好內(nèi)存緩存的沒變化,下面分析的是最新的源碼中的部分,我們在使用中可以不自行配置硬盤緩存策略,直接用DefaultConfigurationFactory中的就行了
我們看DefaultConfigurationFactory這個類的createDiskCache()方法

/** 
 * 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(...)配置。

源代碼解讀

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);   
大部分的時候我們都是使用上面的代碼去加載圖片,我們先看下

public void displayImage(String uri, ImageView imageView, DisplayImageOptions options) { 
  displayImage(uri, new ImageViewAware(imageView), options, null, null); 
 } 

從上面的代碼中,我們可以看出,它會將ImageView轉(zhuǎn)換成ImageViewAware, ImageViewAware主要是做什么的呢?該類主要是將ImageView進(jìn)行一個包裝,將ImageView的強引用變成弱引用,當(dāng)內(nèi)存不足的時候,可以更好的回收ImageView對象,還有就是獲取ImageView的寬度和高度。這使得我們可以根據(jù)ImageView的寬高去對圖片進(jìn)行一個裁剪,減少內(nèi)存的使用。
接下來看具體的displayImage方法啦,由于這個方法代碼量蠻多的,所以這里我分開來讀

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中進(jìn)行的
12-21行主要是針對url為空的時候做的處理,第13行代碼中,ImageLoaderEngine中存在一個HashMap,用來記錄正在加載的任務(wù),加載圖片的時候會將ImageView的id和圖片的url加上尺寸加入到HashMap中,加載完成之后會將其移除,然后將DisplayImageOptions的imageResForEmptyUri的圖片設(shè)置給ImageView,最后回調(diào)給ImageLoadingListener接口告訴它這次任務(wù)完成了。

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行從內(nèi)存緩存中獲取Bitmap對象,我們可以再ImageLoaderConfiguration中配置內(nèi)存緩存邏輯,默認(rèn)使用的是LruMemoryCache,這個類我在前面的文章中講過
第11行中有一個判斷,我們?nèi)绻贒isplayImageOptions中設(shè)置了postProcessor就進(jìn)入true邏輯,不過默認(rèn)postProcessor是為null的,BitmapProcessor接口主要是對Bitmap進(jìn)行處理,這個框架并沒有給出相對應(yīng)的實現(xiàn),如果我們有自己的需求的時候可以自己實現(xiàn)BitmapProcessor接口(比如將圖片設(shè)置成圓形的)
第22 -23行是將Bitmap設(shè)置到ImageView上面,這里我們可以在DisplayImageOptions中配置顯示需求displayer,默認(rèn)使用的是SimpleBitmapDisplayer,直接將Bitmap設(shè)置到ImageView上面,我們可以配置其他的顯示邏輯, 他這里提供了FadeInBitmapDisplayer(透明度從0-1)RoundedBitmapDisplayer(4個角是圓弧)等, 然后回調(diào)到ImageLoadingListener接口

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不在內(nèi)存緩存,從文件中或者網(wǎng)絡(luò)里面獲取bitmap對象,實例化一個LoadAndDisplayImageTask對象,LoadAndDisplayImageTask實現(xiàn)了Runnable,如果配置了isSyncLoading為true, 直接執(zhí)行LoadAndDisplayImageTask的run方法,表示同步,默認(rèn)是false,將LoadAndDisplayImageTask提交給線程池對象
接下來我們就看LoadAndDisplayImageTask的run(), 這個類還是蠻復(fù)雜的,我們還是一段一段的分析

if (waitIfPaused()) return; 
if (delayIfNeed()) return; 

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

waitIfPaused()

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()的源碼

private boolean isTaskNotActual() { 
  return isViewCollected() || isViewReused(); 
 } 

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

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()方法中

ReentrantLock getLockForUri(String uri) { 
  ReentrantLock lock = uriLocks.get(uri); 
  if (lock == null) { 
   lock = new ReentrantLock(); 
   uriLocks.put(uri, lock); 
  } 
  return lock; 
 } 

從上面可以看出,這個鎖對象與圖片的url是相互對應(yīng)的,為什么要這么做?也行你還有點不理解,不知道大家有沒有考慮過一個場景,假如在一個ListView中,某個item正在獲取圖片的過程中,而此時我們將這個item滾出界面之后又將其滾進(jìn)來,滾進(jìn)來之后如果沒有加鎖,該item又會去加載一次圖片,假設(shè)在很短的時間內(nèi)滾動很頻繁,那么就會出現(xiàn)多次去網(wǎng)絡(luò)上面請求圖片,所以這里根據(jù)圖片的Url去對應(yīng)一個ReentrantLock對象,讓具有相同Url的請求就會在第7行等待,等到這次圖片加載完成之后,ReentrantLock就被釋放,剛剛那些相同Url的請求就會繼續(xù)執(zhí)行第7行下面的代碼
來到第12行,它們會先從內(nèi)存緩存中獲取一遍,如果內(nèi)存緩存中沒有在去執(zhí)行下面的邏輯,所以ReentrantLock的作用就是避免這種情況下重復(fù)的去從網(wǎng)絡(luò)上面請求圖片。
第14行的方法tryLoadBitmap(),這個方法確實也有點長,我先告訴大家,這里面的邏輯是先從文件緩存中獲取有沒有Bitmap對象,如果沒有在去從網(wǎng)絡(luò)中獲取,然后將bitmap保存在文件系統(tǒng)中,我們還是具體分析下

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())); 
   } 

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

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,就去網(wǎng)絡(luò)上面獲取Bitmap,來到第6行代碼是否配置了DisplayImageOptions的isCacheOnDisk,表示是否需要將Bitmap對象保存在文件系統(tǒng)中,一般我們需要配置為true, 默認(rèn)是false這個要注意下,然后就是執(zhí)行tryCacheImageOnDisk()方法,去服務(wù)器上面拉取圖片并保存在本地文件中

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()方法是負(fù)責(zé)下載圖片,并將其保持到文件緩存中,將下載保存Bitmap的進(jìn)度回調(diào)到IoUtils.CopyListener接口的onBytesCopied(int current, int total)方法中,所以我們可以設(shè)置ImageLoadingProgressListener接口來獲取圖片下載保存的進(jìn)度,這里保存在文件系統(tǒng)中的圖片是原圖
第16-17行,獲取ImageLoaderConfiguration是否設(shè)置保存在文件系統(tǒng)中的圖片大小,如果設(shè)置了maxImageWidthForDiskCache和maxImageHeightForDiskCache,會調(diào)用resizeAndSaveImage()方法對圖片進(jìn)行裁剪然后在替換之前的原圖,保存裁剪后的圖片到文件系統(tǒng)的,之前有同學(xué)問過我說這個框架保存在文件系統(tǒng)的圖片都是原圖,怎么才能保存縮略圖,只要在Application中實例化ImageLoaderConfiguration的時候設(shè)置maxImageWidthForDiskCache和maxImageHeightForDiskCache就行了

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進(jìn)行處理,這個需要自行實現(xiàn),14-17就是將圖片保存到內(nèi)存緩存中去

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

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

@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被回收了或者被重用了,回調(diào)給ImageLoadingListener接口,否則就調(diào)用BitmapDisplayer去顯示Bitmap
文章寫到這里就已經(jīng)寫完了,不知道大家對這個開源框架有沒有進(jìn)一步的理解,這個開源框架設(shè)計也很靈活,用了很多的設(shè)計模式,比如建造者模式,裝飾模式,代理模式,策略模式等等,這樣方便我們?nèi)U展,實現(xiàn)我們想要的功能。

  • Android開發(fā)Jetpack組件LiveData使用講解

    Android開發(fā)Jetpack組件LiveData使用講解

    LiveData是Jetpack組件的一部分,更多的時候是搭配ViewModel來使用,相對于Observable,LiveData的最大優(yōu)勢是其具有生命感知的,換句話說,LiveData可以保證只有在組件( Activity、Fragment、Service)處于活動生命周期狀態(tài)的時候才會更新數(shù)據(jù)
    2022-08-08
  • MobLink?Android?快速集成指南

    MobLink?Android?快速集成指南

    這篇文章主要為大家介紹了MobLink?Android?快速集成指南,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-10-10
  • Android 中LayoutInflater.inflate()方法的介紹

    Android 中LayoutInflater.inflate()方法的介紹

    這篇文章主要介紹了Android 中LayoutInflater.inflate()方法的介紹的相關(guān)資料,希望通過本文大家能掌握這部分內(nèi)容,需要的朋友可以參考下
    2017-09-09
  • android?viewpager實現(xiàn)輪播效果

    android?viewpager實現(xiàn)輪播效果

    這篇文章主要為大家詳細(xì)介紹了android?viewpager實現(xiàn)輪播效果,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2022-06-06
  • AndroidManifest.xml <uses-feature>和<uses-permisstion>分析及比較

    AndroidManifest.xml <uses-feature>和<uses-permisstio

    這篇文章主要介紹了AndroidManifest.xml <uses-feature>和<uses-permisstion>分析及比較的相關(guān)資料,需要的朋友可以參考下
    2017-06-06
  • 淺談Android Studio 解析XML的三種方法

    淺談Android Studio 解析XML的三種方法

    這篇文章主要介紹了淺談Android Studio 解析XML的三種方法,Android Studio 解析XML常見的三種方式:DOM PULL SAX,非常具有實用價值,需要的朋友可以參考下
    2018-07-07
  • Android中實現(xiàn)多線程操作的幾種方式

    Android中實現(xiàn)多線程操作的幾種方式

    多線程一直是一個老大難的問題,首先因為它難以理解,其次在實際工作中我們需要面對的關(guān)于線程安全問題也并不常見,今天就來總結(jié)一下實現(xiàn)多線程的幾種方式,感興趣的可以了解一下
    2021-06-06
  • 簡單實現(xiàn)Android放大鏡效果

    簡單實現(xiàn)Android放大鏡效果

    這篇文章主要教大家簡單實現(xiàn)Android放大鏡效果,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2017-12-12
  • Android開發(fā)中超好用的正則表達(dá)式工具類RegexUtil完整實例

    Android開發(fā)中超好用的正則表達(dá)式工具類RegexUtil完整實例

    這篇文章主要介紹了Android開發(fā)中超好用的正則表達(dá)式工具類RegexUtil,結(jié)合完整實例形式分析了Android正則表達(dá)式常見操作技巧,包括針對證件號、銀行賬號、手機號、郵編等的正則判斷相關(guān)操作技巧,需要的朋友可以參考下
    2017-11-11
  • 最新評論