轉載請注明本文出自xiaanming的部落格(http://blog.csdn.net/xiaanming/article/details/26810303),請尊重他人的辛勤勞動成果,謝謝!
相信大家平時做Android應用的時候,多少會接觸到異步加載圖檔,或者加載大量圖檔的問題,而加載圖檔我們常常會遇到許多的問題,比如說圖檔的錯亂,OOM等問題,對于新手來說,這些問題解決起來會比較吃力,是以就有很多的開源圖檔加載架構應運而生,比較著名的就是Universal-Image-Loader,相信很多朋友都聽過或者使用過這個強大的圖檔加載架構,今天這篇文章就是對這個架構的基本介紹以及使用,主要是幫助那些沒有使用過這個架構的朋友們。該項目存在于Github上面https://github.com/nostra13/Android-Universal-Image-Loader,我們可以先看看這個開源庫存在哪些特征
- 多線程下載下傳圖檔,圖檔可以來源于網絡,檔案系統,項目檔案夾assets中以及drawable中等
- 支援随意的配置ImageLoader,例如線程池,圖檔下載下傳器,記憶體緩存政策,硬碟緩存政策,圖檔顯示選項以及其他的一些配置
- 支援圖檔的記憶體緩存,檔案系統緩存或者SD卡緩存
- 支援圖檔下載下傳過程的監聽
- 根據控件(ImageView)的大小對Bitmap進行裁剪,減少Bitmap占用過多的記憶體
- 較好的控制圖檔的加載過程,例如暫停圖檔加載,重新開始加載圖檔,一般使用在ListView,GridView中,滑動過程中暫停加載圖檔,停止滑動的時候去加載圖檔
- 提供在較慢的網絡下對圖檔進行加載
當然上面列舉的特性可能不全,要想了解一些其他的特性隻能通過我們的使用慢慢去發現了,接下來我們就看看這個開源庫的簡單使用吧
建立一個Android項目,下載下傳JAR包添加到工程libs目錄下
建立一個MyApplication繼承Application,并在onCreate()中建立ImageLoader的配置參數,并初始化到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();
//建立預設的ImageLoader配置參數
ImageLoaderConfiguration configuration = ImageLoaderConfiguration
.createDefault(this);
//Initialize ImageLoader with configuration.
ImageLoader.getInstance().init(configuration);
}
}
ImageLoaderConfiguration是圖檔加載器ImageLoader的配置參數,使用了建造者模式,這裡是直接使用了createDefault()方法建立一個預設的ImageLoaderConfiguration,當然我們還可以自己設定ImageLoaderConfiguration,設定如下
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檔案
<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的布局檔案
[html] view plain copy
<?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()方法來加載網絡圖檔
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接口方法的空實作,使用的是預設擴充卡模式
.
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來加載網絡圖檔,在實際的開發中,我們并不會這麼使用,那我們平常會怎麼使用呢?我們會用到DisplayImageOptions,他可以配置一些圖檔顯示的選項,比如圖檔在加載中ImageView顯示的圖檔,是否需要使用記憶體緩存,是否需要使用檔案緩存等等,可供我們選擇的配置如下
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來配置顯示圖檔的一些選項,這裡我添加了将圖檔緩存到記憶體中已經緩存圖檔到檔案系統中,這樣我們就不用擔心每次都從網絡中去加載圖檔了,是不是很友善呢,但是DisplayImageOptions選項中有些選項對于loadImage()方法是無效的,比如showImageOnLoading, showImageForEmptyUri等,
displayImage()加載圖檔
接下來我們就來看看網絡圖檔加載的另一個方法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接口,我們也不需要手動設定ImageView顯示Bitmap對象,直接将ImageView作為參數傳遞到displayImage()中就行了,圖檔顯示的配置選項中,我們添加了一個圖檔加載中ImageVIew上面顯示的圖檔,以及圖檔加載出現錯誤顯示的圖檔,效果如下,剛開始顯示ic_stub圖檔,如果圖檔加載成功顯示圖檔,加載産生錯誤顯示ic_error
這個方法使用起來比較友善,而且使用displayImage()方法 他會根據控件的大小和imageScaleType來自動裁剪圖檔,我們修改下MyApplication,開啟Log列印
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接口就行了,代碼如下
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稍加的改變下就行了,下面是加載檔案系統的圖檔
//顯示圖檔的配置
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擷取到輸入流
[java] view plain copy
//圖檔來源于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滑動過程中停止去加載圖檔,該類使用的是代理模式
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設定的值來裁剪圖檔
注:這篇文章是轉載别人文章,僅供學習!!