主頁: https://github.com/nostra13/Android-Universal-Image-Loader
特性:
- 多線程圖片加載(同步/異步)
- 可自由定製圖片加載方式(thread executors, downloader, decoder, memory and disk cache, display image options, etc.)
- 可自由定製圖片顯示方式(stub images, caching switch, decoding options, Bitmap processing and displaying, etc)
- 圖片緩存的處理(內存緩存 / 硬盤緩存(本機 / SD卡))
- 監聽圖片加載進度
工作流程
常用方法
顯示圖片
ImageLoader.getInstance().loadImage(String uri, ImageLoadingListener listener)
//SimpleImageLoadingListener是ImageLoadingListener的空實現
displayImage(String uri, ImageView imageView)
displayImage(String uri, ImageView imageView, DisplayImageOptions options)
displayImage(String uri, ImageView imageView, DisplayImageOptions options,
ImageLoadingListener listener, ImageLoadingProgressListener progressListener)
加載其他圖片
// 圖片來自本機文件
String imageUrl = ImageDownloader.Scheme.FILE.wrap("/mnt/sdcard/image.png");
// 圖片來自Content Provider
String contentURL = ImageDownloader.Scheme.CONTENT.wrap("/media/external/audio/albumart/13");
//圖片來源於assets
String assetsUrl = ImageDownloader.Scheme.ASSETS.wrap("image.png");
//圖片來源於drawable
String drawableUrl = ImageDownloader.Scheme.DRAWABLE.wrap("R.drawable.image");
可處理的URI類型
"http://site.com/image.png" // 網絡地址
"file:///mnt/sdcard/image.png" // SD卡
"file:///mnt/sdcard/video.mp4" // SD卡 (視頻縮略圖)
"content://media/external/images/media/13" // content provider
"content://media/external/video/media/13" // content provider (視頻縮略圖)
"assets://image.png" // assets資源
"drawable://" + R.drawable.img // drawables資源 (不包含.9圖)
使用步驟:
- 1.添加依賴
compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.4'
- 2.添加權限
如需要請求網絡圖片,添加
<uses-permission android:name="android.permission.INTERNET" />
如需要SD卡緩存,添加
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
- 3.初始化配置 , 在調用UIL前必須初始化配置
ImageLoaderConfiguration configuration = ImageLoaderConfiguration.createDefault(this);
ImageLoader.getInstance().init(configuration);
注意事項:
1.默認情況UIL是沒有緩存功能的 , 所以需要在構造DisplayImageOptions時打開緩存功能 .cacheInMemory(), .cacheOnDisk()
2.如果要緩存圖片到本地硬盤 , 不要忘記添加SD卡讀寫權限
3.如果發生OOM異常,參考如下處理
- 縮小線程池的大小, ImageLoaderConfiguration. threadPoolSize() , 推薦值爲1-5
- 指定圖片質量時,使用RGB_565, DisplayImageOptions. bitmapConfig(Bitmap.Config.RGB_565)
- 推薦使用DisplayImageOptions.imageScaleType(ImageScaleType.EXACTLY)
- 使用diskCacheExtraOptions時,推薦參數爲ImageLoaderConfiguration.diskCacheExtraOptions(480, 320, null)
4.UIL已實現的內存緩存配置類.用於ImageLoaderConfiguration memoryCache()
僅強引用 LruMemoryCache
強引用 + 弱引用
UsingFreqLimitedMemoryCache
LRULimitedMemoryCache
FIFOLimitedMemoryCache
LargestLimitedMemoryCache
LimitedAgeMemoryCache
僅弱引用 WeakMemoryCache
5.UIL已實現的硬盤緩存配置類,用於ImageLoaderConfiguration diskCache()
UnlimitedDiscCache (默認值)
LruDiskCache
LimitedAgeDiscCache6.UIL已實現的圖片顯示類, 用於DisplayImageOptions displayer()
RoundedBitmapDisplayer (圓角圖片) 使用該屬性時,ImageView必須指定寬高
FadeInBitmapDisplayer (漸顯圖片)7.爲了避免在可滾動視圖中(ListView / GridView)發生OOM異常,請使用PauseOnScrollListener , 如
boolean pauseOnScroll = false; // or true
boolean pauseOnFling = true; // or false
PauseOnScrollListener listener = new PauseOnScrollListener(imageLoader, pauseOnScroll, pauseOnFling);
listView.setOnScrollListener(listener);
Configuration 參數詳解
File cacheDir = StorageUtils.getCacheDirectory(context); // 自定義緩存文件夾
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)
.memoryCacheExtraOptions(480, 800) // 指定緩存到內存時圖片的大小,默認是屏幕尺寸的長寬
.diskCacheExtraOptions(480, 800, null) // 指定緩存到硬盤時圖片的大小,並不建議使用
.taskExecutor(new Executor()) // 自定義一個線程來加載和顯示圖片
.taskExecutorForCachedImages(new Executor())// 自定義一個線程來緩存圖片
.threadPoolSize(3) // default, 指定線程池大小
.threadPriority(Thread.NORM_PRIORITY - 2) // default ,指定線程優先級
.tasksProcessingOrder(QueueProcessingType.FIFO) // default , 指定加載顯示圖片的任務隊列的類型
.denyCacheImageMultipleSizesInMemory() // 禁止在內存中緩存同一張圖片的多個尺寸類型
.memoryCache(new LruMemoryCache(2 * 1024 * 1024)) // 指定內存緩存的大小,默認值爲1/8 應用的最大可用內存
.memoryCacheSize(2 * 1024 * 1024)
.memoryCacheSizePercentage(13) // default
.diskCache(new UnlimitedDiskCache(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() // 是否顯示Log
.build();
Display Options 參數詳解
DisplayImageOptions options = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.ic_stub) // 圖片正在加載時顯示的圖片資源ID
.showImageForEmptyUri(R.drawable.ic_empty) // URI爲空時顯示的圖片資源ID
.showImageOnFail(R.drawable.ic_error) // 圖片加載失敗時顯示的圖片資源ID
.resetViewBeforeLoading(false) // default 圖片在下載前是否重置,復位
.delayBeforeLoading(1000) // 圖片開始加載前的延時.默認是0
.cacheInMemory(false) // default , 是否緩存在內存中, 默認不緩存
.cacheOnDisk(false) // default , 是否緩存在硬盤 , 默認不緩存
.preProcessor(new BitmapProcessor) // 設置圖片緩存在內存前的圖片處理器
.postProcessor(new BitmapProcessor) // 設置圖片在緩存到內存以後 , 顯示在界面之前的圖片處理器
.extraForDownloader(...) // 爲圖片下載設置輔助參數
.considerExifParams(false) // default , 設置是否考慮JPEG圖片的EXIF參數信息,默認不考慮
.imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2) // default , 指定圖片縮放的方式,ListView/GridView/Gallery推薦使用此默認值
.bitmapConfig(Bitmap.Config.ARGB_8888) // default , 指定圖片的質量,默認是 ARGB_8888
.decodingOptions(...) // 指定圖片的解碼方式
.displayer(new SimpleBitmapDisplayer()) // default , 設置圖片顯示的方式,用於自定義
.handler(new Handler()) // default ,設置圖片顯示的方式和ImageLoadingListener的監聽, 用於自定義
.build();
示例
1.添加依賴和添加權限
build.gradle文件中
compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.4'
AndroidManifest.xml文件中
<!-- Include following permission if you load images from Internet -->
<uses-permission android:name="android.permission.INTERNET"/>
<!-- Include following permission if you want to cache images on SD card -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
2.java代碼
2.1簡單的寫法
//簡單的寫法
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this).build();
ImageLoader.getInstance().init(config);
ImageLoader imageLoader = ImageLoader.getInstance();
imageLoader.displayImage(URL, imageView);
2.2使用Application初始化ImageLoaderConfiguration和使用自定義Activity父類初始化DisplayImageOptions
用Application統一管理config,避免重複創建
1.創建Application子類,設置config的各項屬性
public class MyApp extends Application {
@Override
public void onCreate() {
super.onCreate();
File cacheDir = StorageUtils.getCacheDirectory(this); // 自定義緩存文件夾
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this)
.memoryCacheExtraOptions(480, 800) // 指定緩存到內存時圖片的大小,默認是屏幕尺寸的長寬
// .diskCacheExtraOptions(480, 800, null) // 指定緩存到硬盤時圖片的大小,並不建議使用
// .taskExecutor(new Executor()) // 自定義一個線程來加載和顯示圖片
// .taskExecutorForCachedImages(new Executor())// 自定義一個線程來緩存圖片
.threadPoolSize(3) // default, 指定線程池大小
.threadPriority(Thread.NORM_PRIORITY - 2) // default ,指定線程優先級
.tasksProcessingOrder(QueueProcessingType.FIFO) // default , 指定加載顯示圖片的任務隊列的類型
.denyCacheImageMultipleSizesInMemory() // 禁止在內存中緩存同一張圖片的多個尺寸類型
.memoryCache(new LruMemoryCache(2 * 1024 * 1024)) // 指定內存緩存的大小,默認值爲1/8 應用的最大可用內存
.memoryCacheSize(2 * 1024 * 1024)
.memoryCacheSizePercentage(13) // default
// .diskCache(new UnlimitedDiskCache(cacheDir)) // default , 指定硬盤緩存的地址
.diskCacheSize(50 * 1024 * 1024) // 指定硬盤緩存的大小
.diskCacheFileCount(100) // 指定硬盤緩存的文件個數
.diskCacheFileNameGenerator(new HashCodeFileNameGenerator()) // default , 指定硬盤緩存時文件名的生成器
.imageDownloader(new BaseImageDownloader(this)) // default , 指定圖片下載器
// .imageDecoder(new BaseImageDecoder()) // default , 指定圖片解碼器
.defaultDisplayImageOptions(DisplayImageOptions.createSimple()) // default , 指定圖片顯示的配置
.writeDebugLogs() // 是否顯示Log
.build();
ImageLoader.getInstance().init(config);
}
}
2.AndroidManifest.xml中指明application
<application
android:name=".MyApp"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<!-- ... -->
</application>
3.創建BaseActivity繼承自Activity,初始化options各項設置
public class BaseActivity extends Activity {
public DisplayImageOptions options;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
options = new DisplayImageOptions.Builder()
.showImageOnLoading(R.mipmap.ic_launcher) // 圖片正在加載時顯示的圖片資源ID
.showImageForEmptyUri(R.mipmap.ic_launcher) // URI爲空時顯示的圖片資源ID
.showImageOnFail(R.mipmap.ic_launcher) // 圖片加載失敗時顯示的圖片資源ID
.resetViewBeforeLoading(false) // default 圖片在下載前是否重置,復位
.delayBeforeLoading(1000) // 圖片開始加載前的延時.默認是0
.cacheInMemory(false) // default , 是否緩存在內存中, 默認不緩存
.cacheOnDisk(false) // default , 是否緩存在硬盤 , 默認不緩存
// .preProcessor(new BitmapProcessor) // 設置圖片緩存在內存前的圖片處理器
// .postProcessor(new BitmapProcessor) // 設置圖片在緩存到內存以後 , 顯示在界面之前的圖片處理器
// .extraForDownloader(...) // 爲圖片下載設置輔助參數
.considerExifParams(false) // default , 設置是否考慮JPEG圖片的EXIF參數信息,默認不考慮
.imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2) // default , 指定圖片縮放的方式,ListView/GridView/Gallery推薦使用此默認值
.bitmapConfig(Bitmap.Config.ARGB_8888) // default , 指定圖片的質量,默認是 ARGB_8888
// .decodingOptions(...) // 指定圖片的解碼方式
.displayer(new SimpleBitmapDisplayer()) // default , 設置圖片顯示的方式,用於自定義
// .handler(new Handler()) // default ,設置圖片顯示的方式和ImageLoadingListener的監聽, 用於自定義
.build();
}
}
4.MainActivity繼承BaseActivity,具體圖片加載
public class MainActivity extends BaseActivity {
private static final String URL = "http://p2.so.qhimg.com/t0146fac2d27cc2b0ac.jpg";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView) findViewById(R.id.imageView);
ImageLoader.getInstance().displayImage(URL, imageView, options);//options --> 可以直接用父類變量
}
}