編輯:關於 Android 程式設計
專案地址:
https://github.com/nostra13/Android-Universal-Image-Loader
UIL(Universal-Image-Loader)是一款專為異步圖片加載、緩存與顯示而生的開源庫。這個既能異步加載又能自動緩存圖片的類,早已被廣大開發者採用,是 Android 生態中最常被使用的幾個開源庫之一。隨手反編譯幾個熱門 App,幾乎都能看到它的蹤影。
同類型的 Picasso 雖然 API 更為友善,卻在自訂能力上有所欠缺;而透過 UIL 的建構器,幾乎每一個環節都能自由配置。其中最关键的一點是:在抓取與緩存大型圖片時,Picasso 容易失敗,而 UIL 則表現得穩健許多。
簡單說明一下這個專案的結構:每一個圖片的加載與顯示任務都運行在獨立執行緒中,除非圖片已緩存在記憶體裡,那種情況下會立即顯示。若所需圖片緩存在本地,則會開啟獨立的執行緒佇列;若緩存中找不到對應圖片,任務執行緒便會從執行緒池中取得,因此快速顯示緩存圖片時不會有明顯卡頓。



由於源碼中無論是 loadImageSync 還是 loadImage,最終都會透過 displayImage 來加載,我們不妨一起看看它的整體流程:

Maven:
com.nostra13.universalimageloader universal-image-loader1.9.3
Gradle:
compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.3'
由於加載過程需要透過網路獲取圖片,並且涉及緩存寫入,因此這兩個權限是必須的。
// Create global configuration and initialize ImageLoader with this config ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this) ... .build(); ImageLoader.getInstance().init(config);
https://site.com/image.png // from Web file:///mnt/sdcard/image.png // from SD card file:///mnt/sdcard/video.mp4 // from SD card (video thumbnail) content://media/external/images/media/13 // from content provider content://media/external/video/media/13 // from content provider (video thumbnail) assets://image.png // from assets drawable:// + R.drawable.img // from drawables (non-9patch images)
NOTE: 只有在確實需要時才使用 drawable://。載入 drawable 時,請優先考慮原生做法 ImageView.setImageResource(...),而非透過 ImageLoader。
imageLoader.displayImage(imageUri, imageView); imageLoader.loadImage(imageUri, new SimpleImageLoadingListener() { @Override public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) { // Do whatever you want with Bitmap } }); // Load image, decode it to Bitmap and return Bitmap synchronously Bitmap bmp = imageLoader.loadImageSync(imageUri); // Load image, decode it to Bitmap and return Bitmap to callback ImageSize targetSize = new ImageSize(80, 50); // result Bitmap will be fit to this size imageLoader.loadImage(imageUri, targetSize, options, new SimpleImageLoadingListener() { @Override public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) { // Do whatever you want with Bitmap } }); // Load image, decode it to Bitmap and return Bitmap synchronously ImageSize targetSize = new ImageSize(80, 50); // result Bitmap will be fit to this size Bitmap bmp = imageLoader.loadImageSync(imageUri, targetSize, options);此外,還可以透過 ImageLoadingProgressListener 來監聽加載進度。
ImageLoaderConfiguration 應該作為 Application 級別的全域物件,只需配置一次。
// DON'T COPY THIS CODE TO YOUR PROJECT! This is just example of ALL options using. // See the sample project how to use ImageLoader correctly. File cacheDir = StorageUtils.getCacheDirectory(context); ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context) .memoryCacheExtraOptions(480, 800) // default = device screen dimensions 推薦 .diskCacheExtraOptions(480, 800, null) //.推薦diskCacheExtraOptions(480, 800, null) .taskExecutor(...) .taskExecutorForCachedImages(...) .threadPoolSize(3) // default 推薦1-5 .threadPriority(Thread.NORM_PRIORITY - 2) // default .tasksProcessingOrder(QueueProcessingType.FIFO) // default .denyCacheImageMultipleSizesInMemory() //設置內存緩存不允許緩存一張圖片的多個尺寸,默認允許。 .memoryCache(new LruMemoryCache(2 * 1024 * 1024)) //使用強引用的緩存使用它,不過推薦使用weak與strong引用結合的UsingFreqLimitedMemoryCache或者使用全弱引用的WeakMemoryCache .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();
File cacheDir = StorageUtils.getOwnCacheDirectory(getApplicationContext(), imageloader/Cache);
.diskCache(new UnlimitedDiscCache(cacheDir))//自定義緩存路徑
// DON'T COPY THIS CODE TO YOUR PROJECT! This is just example of ALL options using. // See the sample project how to use ImageLoader correctly. 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 推薦.imageScaleType(ImageScaleType.EXACTLY) 節省內存 .bitmapConfig(Bitmap.Config.ARGB_8888) // default 推薦.bitmapConfig(Bitmap.Config.RGB_565)節省內存 .decodingOptions(...) .displayer(new SimpleBitmapDisplayer()) // default //推薦使用RoundedBitmapDisplayer (Displays bitmap with rounded corners)和FadeInBitmapDisplayer (Displays image with fade in animation .handler(new Handler()) // default .build();
以上配置中的關鍵項說明:
1).imageScaleType(ImageScaleType imageScaleType) 用於設置圖片的縮放方式,可選類型有:
2).displayer(BitmapDisplayer displayer) 用於設置圖片的顯示方式:
1、緩存預設情況下並未啟用,需透過 DisplayImageOptions 手動開啟。
// Create default options which will be used for every // displayImage(...) call if no options will be passed to this method DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder() ... .cacheInMemory(true) .cacheOnDisk(true) ... .build();ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext()) ... .defaultDisplayImageOptions(defaultOptions) ... .build();ImageLoader.getInstance().init(config); // Do it on Application start
// Then later, when you want to display image ImageLoader.getInstance().displayImage(imageUrl, imageView); // Default options will be used
也可以在呼叫時直接傳入選項:
DisplayImageOptions options = new DisplayImageOptions.Builder() ... .cacheInMemory(true) .cacheOnDisk(true) ... .build(); ImageLoader.getInstance().displayImage(imageUrl, imageView, options); // Incoming options will be used
2、為了避免 list(ListView、GridView 等)滾動時出現卡頓,可使用 PauseOnScrollListener。
boolean pauseOnScroll = false; // or true boolean pauseOnFling = true; // or false PauseOnScrollListener listener = new PauseOnScrollListener(imageLoader, pauseOnScroll, pauseOnFling); listView.setOnScrollListener(listener);
1.上述兩個權限務必加入,否則會出錯。
2.ImageLoaderConfiguration 必須配置並在全域初始化 ImageLoader.getInstance().init(config),否則同樣會報錯。
3.ImageLoader 會依據 ImageView 的 height、width 來確定圖片顯示的寬高。
4.若經常出現 OOM(這一點值得特別留意),可嘗試:
①調小執行緒池大小(.threadPoolSize),建議 1-5;
②以 .bitmapConfig(Bitmap.config.RGB_565) 取代 ARGB_8888;
③採用 .imageScaleType(ImageScaleType.IN_SAMPLE_INT) 或 .imageScaleType(ImageScaleType.EXACTLY);
④避免使用 RoundedBitmapDisplayer,它會建立新的 ARGB_8888 格式 Bitmap 物件;
⑤使用 .memoryCache(new WeakMemoryCache()),而非 .cacheInMemory()。
Android 動畫開發實踐:View 動畫、屬性動畫與幀動畫
動畫讓介面更有生命力 好的動畫能讓操作更直覺,也能降低畫面切換的生硬感。Android 常見動畫可分為 View 動畫、屬性動畫與幀動畫,三者適用場景不同。 View 動
天氣 App 布局練習:用 GridView 呈現空氣指標
本篇以一個天氣 App 的空氣品質面板為例,重點練習 GridView 的搭配使用,示範如何把一組數據以三欄網格的形式呈現出來。 一、MainActivity.jav
iOS 開發筆記:UIScrollView 用法全解與輪播圖實作
目錄: UIScrollView 的常見屬性 UIScrollView 的常用代理方法 UIScrollView 的縮放 UIScrollView 和 UIPageCon
Android 開發實戰:用 jsoup 解析並抓取 HTML 頁面
在 Android 開發過程中,抓取、解析與展示網頁內容幾乎是難免的課題。本文就透過 jsoup 這個輕巧好用的 Java 函式庫,示範如何抓取 cnbeta.com 網