Android 框架練成 教你打造高效的圖片加載框架

一、概述

優秀的圖片加載框架不要太多,什麼UIL , Volley ,Picasso,Imageloader等等。可是做爲一名合格的程序猿,必須懂其中的實現原理,因而乎,今天我就帶你們一塊兒來設計一個加載網絡、本地的圖片框架。有人可能會說,本身寫會不會很渣,運行效率,內存溢出神馬的。放心,咱們拿demo說話,拼得就是速度,奏事這麼任性。html

好了,若是你看過以前的博文,相似Android Handler 異步消息處理機制的妙用 建立強大的圖片加載類,可能會對接下來文章理解會有很大的幫助。沒有的話,就跟我往下繼續走吧,也不要去看了。java

關於加載本地圖片,固然了,我手機圖片比較少,7000來張:android

一、首先確定不能內存溢出,可是尼瑪如今像素那麼高,怎麼才能保證呢?我相信利用LruCache統一管理你的圖片是個不二的選擇,全部的圖片從LruCache裏面取,保證全部的圖片的內存不會超過預設的空間。緩存

二、加載速度要剛剛的,我一用力,滑動到3000張的位置,你要是還在從第一張給我加載,尼瑪,你覺得我打dota呢。因此咱們須要引入加載策略,咱們不能FIFO,咱們選擇LIFO,當前呈現給用戶的,最新加載;當前未呈現的,選擇加載。微信

三、使用方便。通常圖片都會使用GridView做爲控件,在getView裏面進行圖片加載,固然了爲了避免錯亂,可能還須要用戶去本身setTag,本身寫回調設置圖片。固然了,咱們不須要這麼麻煩,一句話IoadImage(imageview,path)便可,剩下的請交給咱們的圖片加載框架處理。網絡

作到以上幾點,關於本地的圖片加載應該就木有什麼問題了。架構

關於加載網絡圖片,其實原理差很少,就多了個是否啓用硬盤緩存的選項,若是啓用了,加載時,先從內存中查找,而後從硬盤上找,最後去網絡下載。下載完成後,別忘了寫入硬盤,加入內存緩存。若是沒有啓用,那麼就直接從網絡壓縮獲取,加入內存便可。app

二、效果圖

終於扯完了,接下來,簡單看個效果圖,關於加載本地圖片的效果圖:能夠從Android 超高仿微信圖片選擇器 圖片該這麼加載這篇博客中下載Demo運行。框架

下面演示一個網絡加載圖片的例子:異步


80多張從網絡加載的圖片,能夠看到我直接拖到最後,基本是呈如今用戶眼前的最早加載,要是從第一張到80多,估計也是醉了。

此外:圖片來自老郭的博客,感謝!!!ps:若是你以爲圖片不勁爆,Day Day Up找老郭去。

三、徹底解析


一、關於圖片的壓縮

不論是從網絡仍是本地的圖片,加載都須要進行壓縮,而後顯示:

用戶要你壓縮顯示,會給咱們什麼?一個imageview,一個path,咱們的職責就是壓縮完成後顯示上去。

一、本地圖片的壓縮


a、得到imageview想要顯示的大小

想要壓縮,咱們第一步應該是得到imageview想要顯示的大小,沒大小確定沒辦法壓縮?

那麼如何得到imageview想要顯示的大小呢?

  1. /** 
  2.      * 根據ImageView獲適當的壓縮的寬和高 
  3.      *  
  4.      * @param imageView 
  5.      * @return 
  6.      */  
  7.     public static ImageSize getImageViewSize(ImageView imageView)  
  8.     {  
  9.   
  10.         ImageSize imageSize = new ImageSize();  
  11.         DisplayMetrics displayMetrics = imageView.getContext().getResources()  
  12.                 .getDisplayMetrics();  
  13.   
  14.         LayoutParams lp = imageView.getLayoutParams();  
  15.   
  16.         int width = imageView.getWidth();// 獲取imageview的實際寬度  
  17.         if (width <= 0)  
  18.         {  
  19.             width = lp.width;// 獲取imageview在layout中聲明的寬度  
  20.         }  
  21.         if (width <= 0)  
  22.         {  
  23.             // width = imageView.getMaxWidth();// 檢查最大值  
  24.             width = getImageViewFieldValue(imageView, "mMaxWidth");  
  25.         }  
  26.         if (width <= 0)  
  27.         {  
  28.             width = displayMetrics.widthPixels;  
  29.         }  
  30.   
  31.         int height = imageView.getHeight();// 獲取imageview的實際高度  
  32.         if (height <= 0)  
  33.         {  
  34.             height = lp.height;// 獲取imageview在layout中聲明的寬度  
  35.         }  
  36.         if (height <= 0)  
  37.         {  
  38.             height = getImageViewFieldValue(imageView, "mMaxHeight");// 檢查最大值  
  39.         }  
  40.         if (height <= 0)  
  41.         {  
  42.             height = displayMetrics.heightPixels;  
  43.         }  
  44.         imageSize.width = width;  
  45.         imageSize.height = height;  
  46.   
  47.         return imageSize;  
  48.     }  
  49.   
  50.     public static class ImageSize  
  51.     {  
  52.         int width;  
  53.         int height;  
  54.     }  

能夠看到,咱們拿到imageview之後:

首先企圖經過getWidth獲取顯示的寬;有些時候,這個getWidth返回的是0;

那麼咱們再去看看它有沒有在佈局文件中書寫寬;

若是佈局文件中也沒有精確值,那麼咱們再去看看它有沒有設置最大值;

若是最大值也沒設置,那麼咱們只有拿出咱們的終極方案,使用咱們的屏幕寬度;

總之,不能讓它任性,咱們必定要拿到一個合適的顯示值。

能夠看到這裏或者最大寬度,咱們用的反射,而不是getMaxWidth();維薩呢,由於getMaxWidth居然要API 16,我也是醉了;爲了兼容性,咱們採用反射的方案。反射的代碼就不貼了。

b、設置合適的inSampleSize

咱們得到想要顯示的大小,爲了什麼,還不是爲了和圖片的真正的寬高作比較,拿到一個合適的inSampleSize,去對圖片進行壓縮麼。

那麼首先應該是拿到圖片的寬和高:

  1. // 得到圖片的寬和高,並不把圖片加載到內存中  
  2.         BitmapFactory.Options options = new BitmapFactory.Options();  
  3.         options.inJustDecodeBounds = true;  
  4.         BitmapFactory.decodeFile(path, options);  

這三行就成功獲取圖片真正的寬和高了,存在咱們的options裏面;

而後咱們就能夠happy的去計算inSampleSize了:

  1. /** 
  2.      * 根據需求的寬和高以及圖片實際的寬和高計算SampleSize 
  3.      *  
  4.      * @param options 
  5.      * @param width 
  6.      * @param height 
  7.      * @return 
  8.      */  
  9.     public static int caculateInSampleSize(Options options, int reqWidth,  
  10.             int reqHeight)  
  11.     {  
  12.         int width = options.outWidth;  
  13.         int height = options.outHeight;  
  14.   
  15.         int inSampleSize = 1;  
  16.   
  17.         if (width > reqWidth || height > reqHeight)  
  18.         {  
  19.             int widthRadio = Math.round(width * 1.0f / reqWidth);  
  20.             int heightRadio = Math.round(height * 1.0f / reqHeight);  
  21.   
  22.             inSampleSize = Math.max(widthRadio, heightRadio);  
  23.         }  
  24.   
  25.         return inSampleSize;  
  26.     }  

options裏面存了實際的寬和高;reqWidth和reqHeight就是咱們以前獲得的想要顯示的大小;通過比較,獲得一個合適的inSampleSize;

有了inSampleSize:

  1. options.inSampleSize = ImageSizeUtil.caculateInSampleSize(options,  
  2.                 width, height);  
  3.   
  4.         // 使用得到到的InSampleSize再次解析圖片  
  5.         options.inJustDecodeBounds = false;  
  6.         Bitmap bitmap = BitmapFactory.decodeFile(path, options);  
  7.         return bitmap;  

通過這幾行,就完成圖片的壓縮了。

上述是本地圖片的壓縮,那麼若是是網絡圖片呢?

二、網絡圖片的壓縮


a、直接下載存到sd卡,而後採用本地的壓縮方案。這種方式當前是在硬盤緩存開啓的狀況下,若是沒有開啓呢?

b、使用BitmapFactory.decodeStream(is, null, opts);

  1. /** 
  2.      * 根據url下載圖片在指定的文件 
  3.      *  
  4.      * @param urlStr 
  5.      * @param file 
  6.      * @return 
  7.      */  
  8.     public static Bitmap downloadImgByUrl(String urlStr, ImageView imageview)  
  9.     {  
  10.         FileOutputStream fos = null;  
  11.         InputStream is = null;  
  12.         try  
  13.         {  
  14.             URL url = new URL(urlStr);  
  15.             HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
  16.             is = new BufferedInputStream(conn.getInputStream());  
  17.             is.mark(is.available());  
  18.               
  19.             Options opts = new Options();  
  20.             opts.inJustDecodeBounds = true;  
  21.             Bitmap bitmap = BitmapFactory.decodeStream(is, null, opts);  
  22.               
  23.             //獲取imageview想要顯示的寬和高  
  24.             ImageSize imageViewSize = ImageSizeUtil.getImageViewSize(imageview);  
  25.             opts.inSampleSize = ImageSizeUtil.caculateInSampleSize(opts,  
  26.                     imageViewSize.width, imageViewSize.height);  
  27.               
  28.             opts.inJustDecodeBounds = false;  
  29.             is.reset();  
  30.             bitmap = BitmapFactory.decodeStream(is, null, opts);  
  31.   
  32.             conn.disconnect();  
  33.             return bitmap;  
  34.   
  35.         } catch (Exception e)  
  36.         {  
  37.             e.printStackTrace();  
  38.         } finally  
  39.         {  
  40.             try  
  41.             {  
  42.                 if (is != null)  
  43.                     is.close();  
  44.             } catch (IOException e)  
  45.             {  
  46.             }  
  47.   
  48.             try  
  49.             {  
  50.                 if (fos != null)  
  51.                     fos.close();  
  52.             } catch (IOException e)  
  53.             {  
  54.             }  
  55.         }  
  56.   
  57.         return null;  
  58.   
  59.     }  
基本和本地壓縮差很少,也是兩次取樣,固然須要注意一點,咱們的is進行了包裝,以即可以進行reset();直接返回的is是不能使用兩次的。

到此,圖片壓縮說完了。

二、圖片加載框架的架構

咱們的圖片壓縮加載完了,那麼就應該放入咱們的LruCache,而後設置到咱們的ImageView上。

好了,接下來咱們來講說咱們的這個框架的架構;

一、單例,包含一個LruCache用於管理咱們的圖片;

二、任務隊列,咱們每來一次加載圖片的請求,咱們會封裝成Task存入咱們的TaskQueue;

三、包含一個後臺線程,這個線程在第一次初始化實例的時候啓動,而後會一直在後臺運行;任務呢?還記得咱們有個任務隊列麼,有隊列存任務,得有人幹活呀;因此,當每來一次加載圖片請求的時候,咱們同時發一個消息到後臺線程,後臺線程去使用線程池去TaskQueue去取一個任務執行;

四、調度策略;3中說了,後臺線程去TaskQueue去取一個任務,這個任務不是隨便取的,有策略能夠選擇,一個是FIFO,一個是LIFO,我傾向於後者。

好了,基本就這些結構,接下來看咱們具體的實現。

三、具體的實現


一、構造方法

  1. public static ImageLoader getInstance(int threadCount, Type type)  
  2.     {  
  3.         if (mInstance == null)  
  4.         {  
  5.             synchronized (ImageLoader.class)  
  6.             {  
  7.                 if (mInstance == null)  
  8.                 {  
  9.                     mInstance = new ImageLoader(threadCount, type);  
  10.                 }  
  11.             }  
  12.         }  
  13.         return mInstance;  
  14.     }  

這個就不用說了,重點看咱們的構造方法
  1. /** 
  2.  * 圖片加載類 
  3.  *  
  4.  * @author zhy 
  5.  *  
  6.  */  
  7. public class ImageLoader  
  8. {  
  9.     private static ImageLoader mInstance;  
  10.   
  11.     /** 
  12.      * 圖片緩存的核心對象 
  13.      */  
  14.     private LruCache<String, Bitmap> mLruCache;  
  15.     /** 
  16.      * 線程池 
  17.      */  
  18.     private ExecutorService mThreadPool;  
  19.     private static final int DEAFULT_THREAD_COUNT = 1;  
  20.     /** 
  21.      * 隊列的調度方式 
  22.      */  
  23.     private Type mType = Type.LIFO;  
  24.     /** 
  25.      * 任務隊列 
  26.      */  
  27.     private LinkedList<Runnable> mTaskQueue;  
  28.     /** 
  29.      * 後臺輪詢線程 
  30.      */  
  31.     private Thread mPoolThread;  
  32.     private Handler mPoolThreadHandler;  
  33.     /** 
  34.      * UI線程中的Handler 
  35.      */  
  36.     private Handler mUIHandler;  
  37.   
  38.     private Semaphore mSemaphorePoolThreadHandler = new Semaphore(0);  
  39.     private Semaphore mSemaphoreThreadPool;  
  40.   
  41.     private boolean isDiskCacheEnable = true;  
  42.   
  43.     private static final String TAG = "ImageLoader";  
  44.   
  45.     public enum Type  
  46.     {  
  47.         FIFO, LIFO;  
  48.     }  
  49.   
  50.     private ImageLoader(int threadCount, Type type)  
  51.     {  
  52.         init(threadCount, type);  
  53.     }  
  54.   
  55.     /** 
  56.      * 初始化 
  57.      *  
  58.      * @param threadCount 
  59.      * @param type 
  60.      */  
  61.     private void init(int threadCount, Type type)  
  62.     {  
  63.         initBackThread();  
  64.   
  65.         // 獲取咱們應用的最大可用內存  
  66.         int maxMemory = (int) Runtime.getRuntime().maxMemory();  
  67.         int cacheMemory = maxMemory / 8;  
  68.         mLruCache = new LruCache<String, Bitmap>(cacheMemory)  
  69.         {  
  70.             @Override  
  71.             protected int sizeOf(String key, Bitmap value)  
  72.             {  
  73.                 return value.getRowBytes() * value.getHeight();  
  74.             }  
  75.   
  76.         };  
  77.   
  78.         // 建立線程池  
  79.         mThreadPool = Executors.newFixedThreadPool(threadCount);  
  80.         mTaskQueue = new LinkedList<Runnable>();  
  81.         mType = type;  
  82.         mSemaphoreThreadPool = new Semaphore(threadCount);  
  83.     }  
  84.   
  85.     /** 
  86.      * 初始化後臺輪詢線程 
  87.      */  
  88.     private void initBackThread()  
  89.     {  
  90.         // 後臺輪詢線程  
  91.         mPoolThread = new Thread()  
  92.         {  
  93.             @Override  
  94.             public void run()  
  95.             {  
  96.                 Looper.prepare();  
  97.                 mPoolThreadHandler = new Handler()  
  98.                 {  
  99.                     @Override  
  100.                     public void handleMessage(Message msg)  
  101.                     {  
  102.                         // 線程池去取出一個任務進行執行  
  103.                         mThreadPool.execute(getTask());  
  104.                         try  
  105.                         {  
  106.                             mSemaphoreThreadPool.acquire();  
  107.                         } catch (InterruptedException e)  
  108.                         {  
  109.                         }  
  110.                     }  
  111.                 };  
  112.                 // 釋放一個信號量  
  113.                 mSemaphorePoolThreadHandler.release();  
  114.                 Looper.loop();  
  115.             };  
  116.         };  
  117.   
  118.         mPoolThread.start();  
  119.     }  

在貼構造的時候,順便貼出全部的成員變量;

在構造中咱們調用init,init中能夠設置後臺加載圖片線程數量和加載策略;init中首先初始化後臺線程initBackThread(),能夠看到這個後臺線程,其實是個Looper最終在那不斷的loop,咱們還初始化了一個mPoolThreadHandler用於發送消息到此線程;

接下來就是初始化mLruCache  , mThreadPool ,mTaskQueue 等;

二、loadImage

構造完成之後,固然是使用了,用戶調用loadImage傳入(final String path, final ImageView imageView,final boolean isFromNet)就能夠完成本地或者網絡圖片的加載。

  1. /** 
  2.      * 根據path爲imageview設置圖片 
  3.      *  
  4.      * @param path 
  5.      * @param imageView 
  6.      */  
  7.     public void loadImage(final String path, final ImageView imageView,  
  8.             final boolean isFromNet)  
  9.     {  
  10.         imageView.setTag(path);  
  11.         if (mUIHandler == null)  
  12.         {  
  13.             mUIHandler = new Handler()  
  14.             {  
  15.                 public void handleMessage(Message msg)  
  16.                 {  
  17.                     // 獲取獲得圖片,爲imageview回調設置圖片  
  18.                     ImgBeanHolder holder = (ImgBeanHolder) msg.obj;  
  19.                     Bitmap bm = holder.bitmap;  
  20.                     ImageView imageview = holder.imageView;  
  21.                     String path = holder.path;  
  22.                     // 將path與getTag存儲路徑進行比較  
  23.                     if (imageview.getTag().toString().equals(path))  
  24.                     {  
  25.                         imageview.setImageBitmap(bm);  
  26.                     }  
  27.                 };  
  28.             };  
  29.         }  
  30.   
  31.         // 根據path在緩存中獲取bitmap  
  32.         Bitmap bm = getBitmapFromLruCache(path);  
  33.   
  34.         if (bm != null)  
  35.         {  
  36.             refreashBitmap(path, imageView, bm);  
  37.         } else  
  38.         {  
  39.             addTask(buildTask(path, imageView, isFromNet));  
  40.         }  
  41.   
  42.     }  

首先咱們爲imageview.setTag;而後初始化一個mUIHandler,不用猜,這個mUIHandler用戶更新咱們的imageview,由於這個方法確定是主線程調用的。

而後調用:getBitmapFromLruCache(path);根據path在緩存中獲取bitmap;若是找到那麼直接去設置咱們的圖片;

  1. private void refreashBitmap(final String path, final ImageView imageView,  
  2.             Bitmap bm)  
  3.     {  
  4.         Message message = Message.obtain();  
  5.         ImgBeanHolder holder = new ImgBeanHolder();  
  6.         holder.bitmap = bm;  
  7.         holder.path = path;  
  8.         holder.imageView = imageView;  
  9.         message.obj = holder;  
  10.         mUIHandler.sendMessage(message);  
  11.     }  

能夠看到,若是找到圖片,則直接使用UIHandler去發送一個消息,固然了攜帶了一些必要的參數,而後UIHandler的handleMessage中完成圖片的設置;

handleMessage中拿到path,bitmap,imageview;記得必需要:

// 將path與getTag存儲路徑進行比較
if (imageview.getTag().toString().equals(path))
{
imageview.setImageBitmap(bm);
}

不然會形成圖片混亂。

若是沒找到,則經過buildTask去新建一個任務,在addTask到任務隊列。

buildTask就比較複雜了,由於還涉及到本地和網絡,因此咱們先看addTask代碼:

  1. private synchronized void addTask(Runnable runnable)  
  2.     {  
  3.         mTaskQueue.add(runnable);  
  4.         // if(mPoolThreadHandler==null)wait();  
  5.         try  
  6.         {  
  7.             if (mPoolThreadHandler == null)  
  8.                 mSemaphorePoolThreadHandler.acquire();  
  9.         } catch (InterruptedException e)  
  10.         {  
  11.         }  
  12.         mPoolThreadHandler.sendEmptyMessage(0x110);  
  13.     }  

很簡單,就是runnable加入TaskQueue,與此同時使用mPoolThreadHandler(這個handler還記得麼,用於和咱們後臺線程交互。)去發送一個消息給後臺線程,叫它去取出一個任務執行;具體代碼:
  1. mPoolThreadHandler = new Handler()  
  2.                 {  
  3.                     @Override  
  4.                     public void handleMessage(Message msg)  
  5.                     {  
  6.                         // 線程池去取出一個任務進行執行  
  7.                         mThreadPool.execute(getTask());  

直接使用mThreadPool線程池,而後使用getTask去取一個任務。
  1. /** 
  2.      * 從任務隊列取出一個方法 
  3.      *  
  4.      * @return 
  5.      */  
  6.     private Runnable getTask()  
  7.     {  
  8.         if (mType == Type.FIFO)  
  9.         {  
  10.             return mTaskQueue.removeFirst();  
  11.         } else if (mType == Type.LIFO)  
  12.         {  
  13.             return mTaskQueue.removeLast();  
  14.         }  
  15.         return null;  
  16.     }  

getTask代碼也比較簡單,就是根據Type從任務隊列頭或者尾進行取任務。

如今你會不會好奇,任務裏面到底什麼代碼?其實咱們也就剩最後一段代碼了buildTask

  1. /** 
  2.      * 根據傳入的參數,新建一個任務 
  3.      *  
  4.      * @param path 
  5.      * @param imageView 
  6.      * @param isFromNet 
  7.      * @return 
  8.      */  
  9.     private Runnable buildTask(final String path, final ImageView imageView,  
  10.             final boolean isFromNet)  
  11.     {  
  12.         return new Runnable()  
  13.         {  
  14.             @Override  
  15.             public void run()  
  16.             {  
  17.                 Bitmap bm = null;  
  18.                 if (isFromNet)  
  19.                 {  
  20.                     File file = getDiskCacheDir(imageView.getContext(),  
  21.                             md5(path));  
  22.                     if (file.exists())// 若是在緩存文件中發現  
  23.                     {  
  24.                         Log.e(TAG, "find image :" + path + " in disk cache .");  
  25.                         bm = loadImageFromLocal(file.getAbsolutePath(),  
  26.                                 imageView);  
  27.                     } else  
  28.                     {  
  29.                         if (isDiskCacheEnable)// 檢測是否開啓硬盤緩存  
  30.                         {  
  31.                             boolean downloadState = DownloadImgUtils  
  32.                                     .downloadImgByUrl(path, file);  
  33.                             if (downloadState)// 若是下載成功  
  34.                             {  
  35.                                 Log.e(TAG,  
  36.                                         "download image :" + path  
  37.                                                 + " to disk cache . path is "  
  38.                                                 + file.getAbsolutePath());  
  39.                                 bm = loadImageFromLocal(file.getAbsolutePath(),  
  40.                                         imageView);  
  41.                             }  
  42.                         } else  
  43.                         // 直接從網絡加載  
  44.                         {  
  45.                             Log.e(TAG, "load image :" + path + " to memory.");  
  46.                             bm = DownloadImgUtils.downloadImgByUrl(path,  
  47.                                     imageView);  
  48.                         }  
  49.                     }  
  50.                 } else  
  51.                 {  
  52.                     bm = loadImageFromLocal(path, imageView);  
  53.                 }  
  54.                 // 三、把圖片加入到緩存  
  55.                 addBitmapToLruCache(path, bm);  
  56.                 refreashBitmap(path, imageView, bm);  
  57.                 mSemaphoreThreadPool.release();  
  58.             }  
  59.   
  60.               
  61.         };  
  62.     }  
  63.       
  64.     private Bitmap loadImageFromLocal(final String path,  
  65.             final ImageView imageView)  
  66.     {  
  67.         Bitmap bm;  
  68.         // 加載圖片  
  69.         // 圖片的壓縮  
  70.         // 一、得到圖片須要顯示的大小  
  71.         ImageSize imageSize = ImageSizeUtil.getImageViewSize(imageView);  
  72.         // 二、壓縮圖片  
  73.         bm = decodeSampledBitmapFromPath(path, imageSize.width,  
  74.                 imageSize.height);  
  75.         return bm;  
  76.     }  

咱們新建任務,說明在內存中沒有找到緩存的bitmap;咱們的任務就是去根據path加載壓縮後的bitmap返回便可,而後加入LruCache,設置回調顯示。

首先咱們判斷是不是網絡任務?

若是是,首先去硬盤緩存中找一下,(硬盤中文件名爲:根據path生成的md5爲名稱)。

若是硬盤緩存中沒有,那麼去判斷是否開啓了硬盤緩存:

開啓了的話:下載圖片,使用loadImageFromLocal本地加載圖片的方式進行加載(壓縮的代碼前面已經詳細說過);

         若是沒有開啓:則直接從網絡獲取(壓縮獲取的代碼,前面詳細說過);

若是不是網絡圖片:直接loadImageFromLocal本地加載圖片的方式進行加載


通過上面,就得到了bitmap;而後加入addBitmapToLruCache,refreashBitmap回調顯示圖片。

  1. /** 
  2.      * 將圖片加入LruCache 
  3.      *  
  4.      * @param path 
  5.      * @param bm 
  6.      */  
  7.     protected void addBitmapToLruCache(String path, Bitmap bm)  
  8.     {  
  9.         if (getBitmapFromLruCache(path) == null)  
  10.         {  
  11.             if (bm != null)  
  12.                 mLruCache.put(path, bm);  
  13.         }  
  14.     }  

到此,咱們全部的代碼就分析完成了;


緩存的圖片位置:在SD卡的Android/data/項目packageName/cache中:



不過有些地方須要注意:就是在代碼中,你會看到一些信號量的身影:

第一個:mSemaphorePoolThreadHandler = new Semaphore(0); 用於控制咱們的mPoolThreadHandler的初始化完成,咱們在使用mPoolThreadHandler會進行判空,若是爲null,會經過mSemaphorePoolThreadHandler.acquire()進行阻塞;當mPoolThreadHandler初始化結束,咱們會調用.release();解除阻塞。

第二個:mSemaphoreThreadPool = new Semaphore(threadCount);這個信號量的數量和咱們加載圖片的線程個數一致;每取一個任務去執行,咱們會讓信號量減一;每完成一個任務,會讓信號量+1,再去取任務;目的是什麼呢?爲何當咱們的任務到來時,若是此時在沒有空閒線程,任務則一直添加到TaskQueue中,當線程完成任務,能夠根據策略去TaskQueue中去取任務,只有這樣,咱們的LIFO纔有意義。


到此,咱們的圖片加載框架就結束了,你能夠嘗試下加載本地,或者去加載網絡大量的圖片,拼一拼加載速度~~~

四、MainActivity

如今是使用的時刻~~

我在MainActivity中,我使用了Fragment,下面我貼下Fragment和佈局文件的代碼,具體的,你們本身看代碼:

  1. package com.example.demo_zhy_18_networkimageloader;  
  2.   
  3. import android.content.Context;  
  4. import android.os.Bundle;  
  5. import android.support.v4.app.Fragment;  
  6. import android.util.Log;  
  7. import android.view.LayoutInflater;  
  8. import android.view.View;  
  9. import android.view.ViewGroup;  
  10. import android.widget.ArrayAdapter;  
  11. import android.widget.GridView;  
  12. import android.widget.ImageView;  
  13.   
  14. import com.zhy.utils.ImageLoader;  
  15. import com.zhy.utils.ImageLoader.Type;  
  16. import com.zhy.utils.Images;  
  17.   
  18. public class ListImgsFragment extends Fragment  
  19. {  
  20.     private GridView mGridView;  
  21.     private String[] mUrlStrs = Images.imageThumbUrls;  
  22.     private ImageLoader mImageLoader;  
  23.   
  24.     @Override  
  25.     public void onCreate(Bundle savedInstanceState)  
  26.     {  
  27.         super.onCreate(savedInstanceState);  
  28.         mImageLoader = ImageLoader.getInstance(3, Type.LIFO);  
  29.     }  
  30.   
  31.     @Override  
  32.     public View onCreateView(LayoutInflater inflater, ViewGroup container,  
  33.             Bundle savedInstanceState)  
  34.     {  
  35.         View view = inflater.inflate(R.layout.fragment_list_imgs, container,  
  36.                 false);  
  37.         mGridView = (GridView) view.findViewById(R.id.id_gridview);  
  38.         setUpAdapter();  
  39.         return view;  
  40.     }  
  41.   
  42.     private void setUpAdapter()  
  43.     {  
  44.         if (getActivity() == null || mGridView == null)  
  45.             return;  
  46.   
  47.         if (mUrlStrs != null)  
  48.         {  
  49.             mGridView.setAdapter(new ListImgItemAdaper(getActivity(), 0,  
  50.                     mUrlStrs));  
  51.         } else  
  52.         {  
  53.             mGridView.setAdapter(null);  
  54.         }  
  55.   
  56.     }  
  57.   
  58.     private class ListImgItemAdaper extends ArrayAdapter<String>  
  59.     {  
  60.   
  61.         public ListImgItemAdaper(Context context, int resource, String[] datas)  
  62.         {  
  63.             super(getActivity(), 0, datas);  
  64.             Log.e("TAG""ListImgItemAdaper");  
  65.         }  
  66.   
  67.         @Override  
  68.         public View getView(int position, View convertView, ViewGroup parent)  
  69.         {  
  70.             if (convertView == null)  
  71.             {  
  72.                 convertView = getActivity().getLayoutInflater().inflate(  
  73.                         R.layout.item_fragment_list_imgs, parent, false);  
  74.             }  
  75.             ImageView imageview = (ImageView) convertView  
  76.                     .findViewById(R.id.id_img);  
  77.             imageview.setImageResource(R.drawable.pictures_no);  
  78.             mImageLoader.loadImage(getItem(position), imageview, true);  
  79.             return convertView;  
  80.         }  
  81.   
  82.     }  
  83.   
  84. }  

能夠看到咱們在getView中,使用mImageLoader.loadImage一行即完成了圖片的加載。


fragment_list_imgs.xml


  1. <GridView xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     xmlns:tools="http://schemas.android.com/tools"  
  3.     android:id="@+id/id_gridview"  
  4.     android:layout_width="match_parent"  
  5.     android:layout_height="match_parent"  
  6.     android:horizontalSpacing="3dp"  
  7.     android:verticalSpacing="3dp"  
  8.     android:numColumns="3"  
  9.    >  
  10.   
  11. </GridView>  

item_fragment_list_imgs.xml

  1. <ImageView xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     xmlns:tools="http://schemas.android.com/tools"  
  3.     android:id="@+id/id_img"  
  4.     android:layout_width="match_parent"  
  5.     android:layout_height="120dp"  
  6.     android:scaleType="centerCrop" >  
  7.   
  8. </ImageView>  

好了,到此結束~~~有任何bug或者意見歡迎留言~


源碼點擊下載




----------------------------------------------------------------------------------------------------------

博主部分視頻已經上線,若是你不喜歡枯燥的文本,請猛戳(初錄,期待您的支持):

一、Android 自定義控件實戰 電商活動中的刮刮卡

二、Android自定義控件實戰  打造Android流式佈局和熱門標籤

三、Android智能機器人「小慕」的實現

四、高仿QQ5.0側滑

五、高仿微信5.2.1主界面及消息提醒

相關文章
相關標籤/搜索