Android 異步加載圖片,使用LruCache和SD卡或手機緩存,效果很是的流暢

轉載請註明出處http://blog.csdn.net/xiaanming/article/details/9825113html

異步加載圖片的例子,網上也比較多,大部分用了HashMap<String, SoftReference<Drawable>> imageCache ,可是如今已經再也不推薦使用這種方式了,由於從 Android 2.3 (API Level 9)開始,垃圾回收器會更傾向於回收持有軟引用或弱引用的對象,這讓軟引用和弱引用變得再也不可靠。另外,Android 3.0 (API Level 11)中,圖片的數據會存儲在本地的內存當中,於是沒法用一種可預見的方式將其釋放,這就有潛在的風險形成應用程序的內存溢出並崩潰,因此我這裏用得是LruCache來緩存圖片,當存儲Image的大小大於LruCache設定的值,系統自動釋放內存,這個類是3.1版本中提供的,若是你是在更早的Android版本中開發,則須要導入android-support-v4的jar包(這裏要注意咯)java


爲何寫這篇文章呢?
android

由於我以前作的項目中,也有異步加載圖片,那時候用得是Thread去下載圖片,每次下載圖片都要new Thread去下載,並且仍是併發去下載,每次都new 一個線程浪費內存,老闆說服務器承受不起這麼多的鏈接,叫我改爲先獲取一張圖片以後再去獲取下一張,這樣子保存與服務器的鏈接爲一個,服務器壓力小了,而後樓主就想到線程池,線程池很好的幫咱們管理併發的問題,併發的問題解決了,但是後面又出問題了,圖片多了就出現OOM(OutOfMemory)異常,以後用了SoftReference,先用SoftReference中獲取圖片,SoftReference沒有就開線程去下載,老闆說你爲何不把圖片在手機上作個緩存呢,因而我用了手機緩存,大概思路就是先從SoftReference中獲取圖片,若是SoftReference沒有就去手機緩存中獲取,手機緩存中沒有就開啓先從去下載,而後成功的解決了OOM的問題,前些天老闆要我重構下代碼,我也以爲以前寫的代碼耦合性太強,早就想改,而後以前看到guolin的Android照片牆應用實現,再多的圖片也不怕崩潰的這篇文章,LruCache和滑動過程當中取消下載任務,停下來的時候纔去下載這2點比較好,值得我學習,而後我就將個人項目異步加載這一塊改了下,發到這裏作個記錄吧,之後相似的異步加載圖片直接拷貝代碼,提交開發的效率數組


這篇文章作了哪些方面的優化緩存

  1. 使用了線程池來管理下載任務服務器

  2. 使用LruCache來緩存圖片網絡

  3. 使用手機來緩存圖片併發

  4. GridView滑動的時候取消下載任務,靜止的時候進行下載,GridView滑動更加的流暢app

  5. 下降了代碼的耦合性,結構更加的清晰,便於之後重用異步

接下來咱們先來看看項目的結構


  • FileUtils 文件操做的工具類,提供保存圖片,獲取圖片,判斷圖片是否存在,刪除圖片的一些方法,這個類比較簡單

[java] view plaincopy在CODE上查看代碼片派生到個人代碼片

  1. package com.example.asyncimageloader;  

  2.   

  3. import java.io.File;  

  4. import java.io.FileOutputStream;  

  5. import java.io.IOException;  

  6.   

  7. import android.content.Context;  

  8. import android.graphics.Bitmap;  

  9. import android.graphics.Bitmap.CompressFormat;  

  10. import android.graphics.BitmapFactory;  

  11. import android.os.Environment;  

  12.   

  13. public class FileUtils {  

  14.     /** 

  15.      * sd卡的根目錄 

  16.      */  

  17.     private static String mSdRootPath = Environment.getExternalStorageDirectory().getPath();  

  18.     /** 

  19.      * 手機的緩存根目錄 

  20.      */  

  21.     private static String mDataRootPath = null;  

  22.     /** 

  23.      * 保存Image的目錄名 

  24.      */  

  25.     private final static String FOLDER_NAME = "/AndroidImage";  

  26.       

  27.       

  28.     public FileUtils(Context context){  

  29.         mDataRootPath = context.getCacheDir().getPath();  

  30.     }  

  31.       

  32.   

  33.     /** 

  34.      * 獲取儲存Image的目錄 

  35.      * @return  

  36.      */  

  37.     private String getStorageDirectory(){  

  38.         return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED) ?  

  39.                 mSdRootPath + FOLDER_NAME : mDataRootPath + FOLDER_NAME;  

  40.     }  

  41.       

  42.     /** 

  43.      * 保存Image的方法,有sd卡存儲到sd卡,沒有就存儲到手機目錄 

  44.      * @param fileName  

  45.      * @param bitmap    

  46.      * @throws IOException 

  47.      */  

  48.     public void savaBitmap(String fileName, Bitmap bitmap) throws IOException{  

  49.         if(bitmap == null){  

  50.             return;  

  51.         }  

  52.         String path = getStorageDirectory();  

  53.         File folderFile = new File(path);  

  54.         if(!folderFile.exists()){  

  55.             folderFile.mkdir();  

  56.         }  

  57.         File file = new File(path + File.separator + fileName);  

  58.         file.createNewFile();  

  59.         FileOutputStream fos = new FileOutputStream(file);  

  60.         bitmap.compress(CompressFormat.JPEG, 100, fos);  

  61.         fos.flush();  

  62.         fos.close();  

  63.     }  

  64.       

  65.     /** 

  66.      * 從手機或者sd卡獲取Bitmap 

  67.      * @param fileName 

  68.      * @return 

  69.      */  

  70.     public Bitmap getBitmap(String fileName){  

  71.         return BitmapFactory.decodeFile(getStorageDirectory() + File.separator + fileName);  

  72.     }  

  73.       

  74.     /** 

  75.      * 判斷文件是否存在 

  76.      * @param fileName 

  77.      * @return 

  78.      */  

  79.     public boolean isFileExists(String fileName){  

  80.         return new File(getStorageDirectory() + File.separator + fileName).exists();  

  81.     }  

  82.       

  83.     /** 

  84.      * 獲取文件的大小 

  85.      * @param fileName 

  86.      * @return 

  87.      */  

  88.     public long getFileSize(String fileName) {  

  89.         return new File(getStorageDirectory() + File.separator + fileName).length();  

  90.     }  

  91.       

  92.       

  93.     /** 

  94.      * 刪除SD卡或者手機的緩存圖片和目錄 

  95.      */  

  96.     public void deleteFile() {  

  97.         File dirFile = new File(getStorageDirectory());  

  98.         if(! dirFile.exists()){  

  99.             return;  

  100.         }  

  101.         if (dirFile.isDirectory()) {  

  102.             String[] children = dirFile.list();  

  103.             for (int i = 0; i < children.length; i++) {  

  104.                 new File(dirFile, children[i]).delete();  

  105.             }  

  106.         }  

  107.           

  108.         dirFile.delete();  

  109.     }  

  110. }<span style="font-family:Times New Roman;font-size:14px;">  

  111. </span>  

[java] view plaincopy在CODE上查看代碼片派生到個人代碼片

  1. package com.example.asyncimageloader;  

  2.   

  3. public class Images {  

  4.   

  5.     public final static String[] imageThumbUrls = new String[] {  

  6.             "https://lh6.googleusercontent.com/-55osAWw3x0Q/URquUtcFr5I/AAAAAAAAAbs/rWlj1RUKrYI/s160-c/A%252520Photographer.jpg",  

  7.             "https://lh4.googleusercontent.com/--dq8niRp7W4/URquVgmXvgI/AAAAAAAAAbs/-gnuLQfNnBA/s160-c/A%252520Song%252520of%252520Ice%252520and%252520Fire.jpg",  

  8.             "https://lh5.googleusercontent.com/-7qZeDtRKFKc/URquWZT1gOI/AAAAAAAAAbs/hqWgteyNXsg/s160-c/Another%252520Rockaway%252520Sunset.jpg",  

  9.             "https://lh3.googleusercontent.com/--L0Km39l5J8/URquXHGcdNI/AAAAAAAAAbs/3ZrSJNrSomQ/s160-c/Antelope%252520Butte.jpg",  

  10.             "https://lh6.googleusercontent.com/-8HO-4vIFnlw/URquZnsFgtI/AAAAAAAAAbs/WT8jViTF7vw/s160-c/Antelope%252520Hallway.jpg",  

  11.             "https://lh4.googleusercontent.com/-WIuWgVcU3Qw/URqubRVcj4I/AAAAAAAAAbs/YvbwgGjwdIQ/s160-c/Antelope%252520Walls.jpg",  

  12.             "https://lh6.googleusercontent.com/-UBmLbPELvoQ/URqucCdv0kI/AAAAAAAAAbs/IdNhr2VQoQs/s160-c/Apre%2525CC%252580s%252520la%252520Pluie.jpg",  

  13.             "https://lh3.googleusercontent.com/-s-AFpvgSeew/URquc6dF-JI/AAAAAAAAAbs/Mt3xNGRUd68/s160-c/Backlit%252520Cloud.jpg",  

  14.             "https://lh5.googleusercontent.com/-bvmif9a9YOQ/URquea3heHI/AAAAAAAAAbs/rcr6wyeQtAo/s160-c/Bee%252520and%252520Flower.jpg",  

  15.             "https://lh5.googleusercontent.com/-n7mdm7I7FGs/URqueT_BT-I/AAAAAAAAAbs/9MYmXlmpSAo/s160-c/Bonzai%252520Rock%252520Sunset.jpg",  

  16.             "https://lh6.googleusercontent.com/-4CN4X4t0M1k/URqufPozWzI/AAAAAAAAAbs/8wK41lg1KPs/s160-c/Caterpillar.jpg",  

  17.             "https://lh3.googleusercontent.com/-rrFnVC8xQEg/URqufdrLBaI/AAAAAAAAAbs/s69WYy_fl1E/s160-c/Chess.jpg",  

  18.             "https://lh5.googleusercontent.com/-WVpRptWH8Yw/URqugh-QmDI/AAAAAAAAAbs/E-MgBgtlUWU/s160-c/Chihuly.jpg",  

  19.             "https://lh5.googleusercontent.com/-0BDXkYmckbo/URquhKFW84I/AAAAAAAAAbs/ogQtHCTk2JQ/s160-c/Closed%252520Door.jpg",  

  20.             "https://lh3.googleusercontent.com/-PyggXXZRykM/URquh-kVvoI/AAAAAAAAAbs/hFtDwhtrHHQ/s160-c/Colorado%252520River%252520Sunset.jpg",  

  21.             "https://lh3.googleusercontent.com/-ZAs4dNZtALc/URquikvOCWI/AAAAAAAAAbs/DXz4h3dll1Y/s160-c/Colors%252520of%252520Autumn.jpg",  

  22.             "https://lh4.googleusercontent.com/-GztnWEIiMz8/URqukVCU7bI/AAAAAAAAAbs/jo2Hjv6MZ6M/s160-c/Countryside.jpg",  

  23.             "https://lh4.googleusercontent.com/-bEg9EZ9QoiM/URquklz3FGI/AAAAAAAAAbs/UUuv8Ac2BaE/s160-c/Death%252520Valley%252520-%252520Dunes.jpg",  

  24.             "https://lh6.googleusercontent.com/-ijQJ8W68tEE/URqulGkvFEI/AAAAAAAAAbs/zPXvIwi_rFw/s160-c/Delicate%252520Arch.jpg",  

  25.             "https://lh5.googleusercontent.com/-Oh8mMy2ieng/URqullDwehI/AAAAAAAAAbs/TbdeEfsaIZY/s160-c/Despair.jpg",  

  26.             "https://lh5.googleusercontent.com/-gl0y4UiAOlk/URqumC_KjBI/AAAAAAAAAbs/PM1eT7dn4oo/s160-c/Eagle%252520Fall%252520Sunrise.jpg",  

  27.             "https://lh3.googleusercontent.com/-hYYHd2_vXPQ/URqumtJa9eI/AAAAAAAAAbs/wAalXVkbSh0/s160-c/Electric%252520Storm.jpg",  

  28.             "https://lh5.googleusercontent.com/-PyY_yiyjPTo/URqunUOhHFI/AAAAAAAAAbs/azZoULNuJXc/s160-c/False%252520Kiva.jpg",  

  29.             "https://lh6.googleusercontent.com/-PYvLVdvXywk/URqunwd8hfI/AAAAAAAAAbs/qiMwgkFvf6I/s160-c/Fitzgerald%252520Streaks.jpg",  

  30.             "https://lh4.googleusercontent.com/-KIR_UobIIqY/URquoCZ9SlI/AAAAAAAAAbs/Y4d4q8sXu4c/s160-c/Foggy%252520Sunset.jpg",  

  31.             "https://lh6.googleusercontent.com/-9lzOk_OWZH0/URquoo4xYoI/AAAAAAAAAbs/AwgzHtNVCwU/s160-c/Frantic.jpg",  

  32.             "https://lh3.googleusercontent.com/-0X3JNaKaz48/URqupH78wpI/AAAAAAAAAbs/lHXxu_zbH8s/s160-c/Golden%252520Gate%252520Afternoon.jpg",  

  33.             "https://lh6.googleusercontent.com/-95sb5ag7ABc/URqupl95RDI/AAAAAAAAAbs/g73R20iVTRA/s160-c/Golden%252520Gate%252520Fog.jpg",  

  34.             "https://lh3.googleusercontent.com/-JB9v6rtgHhk/URqup21F-zI/AAAAAAAAAbs/64Fb8qMZWXk/s160-c/Golden%252520Grass.jpg",  

  35.             "https://lh4.googleusercontent.com/-EIBGfnuLtII/URquqVHwaRI/AAAAAAAAAbs/FA4McV2u8VE/s160-c/Grand%252520Teton.jpg",  

  36.             "https://lh4.googleusercontent.com/-WoMxZvmN9nY/URquq1v2AoI/AAAAAAAAAbs/grj5uMhL6NA/s160-c/Grass%252520Closeup.jpg",  

  37.             "https://lh3.googleusercontent.com/-6hZiEHXx64Q/URqurxvNdqI/AAAAAAAAAbs/kWMXM3o5OVI/s160-c/Green%252520Grass.jpg",  

  38.             "https://lh5.googleusercontent.com/-6LVb9OXtQ60/URquteBFuKI/AAAAAAAAAbs/4F4kRgecwFs/s160-c/Hanging%252520Leaf.jpg",  

  39.             "https://lh4.googleusercontent.com/-zAvf__52ONk/URqutT_IuxI/AAAAAAAAAbs/D_bcuc0thoU/s160-c/Highway%2525201.jpg",  

  40.             "https://lh6.googleusercontent.com/-H4SrUg615rA/URquuL27fXI/AAAAAAAAAbs/4aEqJfiMsOU/s160-c/Horseshoe%252520Bend%252520Sunset.jpg",  

  41.             "https://lh4.googleusercontent.com/-JhFi4fb_Pqw/URquuX-QXbI/AAAAAAAAAbs/IXpYUxuweYM/s160-c/Horseshoe%252520Bend.jpg",  

  42.             "https://lh5.googleusercontent.com/-UGgssvFRJ7g/URquueyJzGI/AAAAAAAAAbs/yYIBlLT0toM/s160-c/Into%252520the%252520Blue.jpg",  

  43.             "https://lh3.googleusercontent.com/-CH7KoupI7uI/URquu0FF__I/AAAAAAAAAbs/R7GDmI7v_G0/s160-c/Jelly%252520Fish%2525202.jpg",  

  44.             "https://lh4.googleusercontent.com/-pwuuw6yhg8U/URquvPxR3FI/AAAAAAAAAbs/VNGk6f-tsGE/s160-c/Jelly%252520Fish%2525203.jpg",  

  45.             "https://lh5.googleusercontent.com/-GoUQVw1fnFw/URquv6xbC0I/AAAAAAAAAbs/zEUVTQQ43Zc/s160-c/Kauai.jpg",  

  46.             "https://lh6.googleusercontent.com/-8QdYYQEpYjw/URquwvdh88I/AAAAAAAAAbs/cktDy-ysfHo/s160-c/Kyoto%252520Sunset.jpg",  

  47.             "https://lh4.googleusercontent.com/-vPeekyDjOE0/URquwzJ28qI/AAAAAAAAAbs/qxcyXULsZrg/s160-c/Lake%252520Tahoe%252520Colors.jpg",  

  48.             "https://lh4.googleusercontent.com/-xBPxWpD4yxU/URquxWHk8AI/AAAAAAAAAbs/ARDPeDYPiMY/s160-c/Lava%252520from%252520the%252520Sky.jpg",  

  49.             "https://lh3.googleusercontent.com/-897VXrJB6RE/URquxxxd-5I/AAAAAAAAAbs/j-Cz4T4YvIw/s160-c/Leica%25252050mm%252520Summilux.jpg",  

  50.             "https://lh5.googleusercontent.com/-qSJ4D4iXzGo/URquyDWiJ1I/AAAAAAAAAbs/k2pBXeWehOA/s160-c/Leica%25252050mm%252520Summilux.jpg",  

  51.             "https://lh6.googleusercontent.com/-dwlPg83vzLg/URquylTVuFI/AAAAAAAAAbs/G6SyQ8b4YsI/s160-c/Leica%252520M8%252520%252528Front%252529.jpg",  

  52.             "https://lh3.googleusercontent.com/-R3_EYAyJvfk/URquzQBv8eI/AAAAAAAAAbs/b9xhpUM3pEI/s160-c/Light%252520to%252520Sand.jpg",  

  53.             "https://lh3.googleusercontent.com/-fHY5h67QPi0/URqu0Cp4J1I/AAAAAAAAAbs/0lG6m94Z6vM/s160-c/Little%252520Bit%252520of%252520Paradise.jpg",  

  54.             "https://lh5.googleusercontent.com/-TzF_LwrCnRM/URqu0RddPOI/AAAAAAAAAbs/gaj2dLiuX0s/s160-c/Lone%252520Pine%252520Sunset.jpg",  

  55.             "https://lh3.googleusercontent.com/-4HdpJ4_DXU4/URqu046dJ9I/AAAAAAAAAbs/eBOodtk2_uk/s160-c/Lonely%252520Rock.jpg",  

  56.             "https://lh6.googleusercontent.com/-erbF--z-W4s/URqu1ajSLkI/AAAAAAAAAbs/xjDCDO1INzM/s160-c/Longue%252520Vue.jpg",  

  57.             "https://lh6.googleusercontent.com/-0CXJRdJaqvc/URqu1opNZNI/AAAAAAAAAbs/PFB2oPUU7Lk/s160-c/Look%252520Me%252520in%252520the%252520Eye.jpg",  

  58.             "https://lh3.googleusercontent.com/-D_5lNxnDN6g/URqu2Tk7HVI/AAAAAAAAAbs/p0ddca9W__Y/s160-c/Lost%252520in%252520a%252520Field.jpg",  

  59.             "https://lh6.googleusercontent.com/-flsqwMrIk2Q/URqu24PcmjI/AAAAAAAAAbs/5ocIH85XofM/s160-c/Marshall%252520Beach%252520Sunset.jpg",  

  60.             "https://lh4.googleusercontent.com/-Y4lgryEVTmU/URqu28kG3gI/AAAAAAAAAbs/OjXpekqtbJ4/s160-c/Mono%252520Lake%252520Blue.jpg",  

  61.             "https://lh4.googleusercontent.com/-AaHAJPmcGYA/URqu3PIldHI/AAAAAAAAAbs/lcTqk1SIcRs/s160-c/Monument%252520Valley%252520Overlook.jpg",  

  62.             "https://lh4.googleusercontent.com/-vKxfdQ83dQA/URqu31Yq_BI/AAAAAAAAAbs/OUoGk_2AyfM/s160-c/Moving%252520Rock.jpg",  

  63.             "https://lh5.googleusercontent.com/-CG62QiPpWXg/URqu4ia4vRI/AAAAAAAAAbs/0YOdqLAlcAc/s160-c/Napali%252520Coast.jpg",  

  64.             "https://lh6.googleusercontent.com/-wdGrP5PMmJQ/URqu5PZvn7I/AAAAAAAAAbs/m0abEcdPXe4/s160-c/One%252520Wheel.jpg",  

  65.             "https://lh6.googleusercontent.com/-6WS5DoCGuOA/URqu5qx1UgI/AAAAAAAAAbs/giMw2ixPvrY/s160-c/Open%252520Sky.jpg",  

  66.             "https://lh6.googleusercontent.com/-u8EHKj8G8GQ/URqu55sM6yI/AAAAAAAAAbs/lIXX_GlTdmI/s160-c/Orange%252520Sunset.jpg",  

  67.             "https://lh6.googleusercontent.com/-74Z5qj4bTDE/URqu6LSrJrI/AAAAAAAAAbs/XzmVkw90szQ/s160-c/Orchid.jpg",  

  68.             "https://lh6.googleusercontent.com/-lEQE4h6TePE/URqu6t_lSkI/AAAAAAAAAbs/zvGYKOea_qY/s160-c/Over%252520there.jpg",  

  69.             "https://lh5.googleusercontent.com/-cauH-53JH2M/URqu66v_USI/AAAAAAAAAbs/EucwwqclfKQ/s160-c/Plumes.jpg",  

  70.             "https://lh3.googleusercontent.com/-eDLT2jHDoy4/URqu7axzkAI/AAAAAAAAAbs/iVZE-xJ7lZs/s160-c/Rainbokeh.jpg",  

  71.             "https://lh5.googleusercontent.com/-j1NLqEFIyco/URqu8L1CGcI/AAAAAAAAAbs/aqZkgX66zlI/s160-c/Rainbow.jpg",  

  72.             "https://lh5.googleusercontent.com/-DRnqmK0t4VU/URqu8XYN9yI/AAAAAAAAAbs/LgvF_592WLU/s160-c/Rice%252520Fields.jpg",  

  73.             "https://lh3.googleusercontent.com/-hwh1v3EOGcQ/URqu8qOaKwI/AAAAAAAAAbs/IljRJRnbJGw/s160-c/Rockaway%252520Fire%252520Sky.jpg",  

  74.             "https://lh5.googleusercontent.com/-wjV6FQk7tlk/URqu9jCQ8sI/AAAAAAAAAbs/RyYUpdo-c9o/s160-c/Rockaway%252520Flow.jpg",  

  75.             "https://lh6.googleusercontent.com/-6cAXNfo7D20/URqu-BdzgPI/AAAAAAAAAbs/OmsYllzJqwo/s160-c/Rockaway%252520Sunset%252520Sky.jpg",  

  76.             "https://lh3.googleusercontent.com/-sl8fpGPS-RE/URqu_BOkfgI/AAAAAAAAAbs/Dg2Fv-JxOeg/s160-c/Russian%252520Ridge%252520Sunset.jpg",  

  77.             "https://lh6.googleusercontent.com/-gVtY36mMBIg/URqu_q91lkI/AAAAAAAAAbs/3CiFMBcy5MA/s160-c/Rust%252520Knot.jpg",  

  78.             "https://lh6.googleusercontent.com/-GHeImuHqJBE/URqu_FKfVLI/AAAAAAAAAbs/axuEJeqam7Q/s160-c/Sailing%252520Stones.jpg",  

  79.             "https://lh3.googleusercontent.com/-hBbYZjTOwGc/URqu_ycpIrI/AAAAAAAAAbs/nAdJUXnGJYE/s160-c/Seahorse.jpg",  

  80.             "https://lh3.googleusercontent.com/-Iwi6-i6IexY/URqvAYZHsVI/AAAAAAAAAbs/5ETWl4qXsFE/s160-c/Shinjuku%252520Street.jpg",  

  81.             "https://lh6.googleusercontent.com/-amhnySTM_MY/URqvAlb5KoI/AAAAAAAAAbs/pFCFgzlKsn0/s160-c/Sierra%252520Heavens.jpg",  

  82.             "https://lh5.googleusercontent.com/-dJgjepFrYSo/URqvBVJZrAI/AAAAAAAAAbs/v-F5QWpYO6s/s160-c/Sierra%252520Sunset.jpg",  

  83.             "https://lh4.googleusercontent.com/-Z4zGiC5nWdc/URqvBdEwivI/AAAAAAAAAbs/ZRZR1VJ84QA/s160-c/Sin%252520Lights.jpg",  

  84.             "https://lh4.googleusercontent.com/-_0cYiWW8ccY/URqvBz3iM4I/AAAAAAAAAbs/9N_Wq8MhLTY/s160-c/Starry%252520Lake.jpg",  

  85.             "https://lh3.googleusercontent.com/-A9LMoRyuQUA/URqvCYx_JoI/AAAAAAAAAbs/s7sde1Bz9cI/s160-c/Starry%252520Night.jpg",  

  86.             "https://lh3.googleusercontent.com/-KtLJ3k858eY/URqvC_2h_bI/AAAAAAAAAbs/zzEBImwDA_g/s160-c/Stream.jpg",  

  87.             "https://lh5.googleusercontent.com/-dFB7Lad6RcA/URqvDUftwWI/AAAAAAAAAbs/BrhoUtXTN7o/s160-c/Strip%252520Sunset.jpg",  

  88.             "https://lh5.googleusercontent.com/-at6apgFiN20/URqvDyffUZI/AAAAAAAAAbs/clABCx171bE/s160-c/Sunset%252520Hills.jpg",  

  89.             "https://lh4.googleusercontent.com/-7-EHhtQthII/URqvEYTk4vI/AAAAAAAAAbs/QSJZoB3YjVg/s160-c/Tenaya%252520Lake%2525202.jpg",  

  90.             "https://lh6.googleusercontent.com/-8MrjV_a-Pok/URqvFC5repI/AAAAAAAAAbs/9inKTg9fbCE/s160-c/Tenaya%252520Lake.jpg",  

  91.             "https://lh5.googleusercontent.com/-B1HW-z4zwao/URqvFWYRwUI/AAAAAAAAAbs/8Peli53Bs8I/s160-c/The%252520Cave%252520BW.jpg",  

  92.             "https://lh3.googleusercontent.com/-PO4E-xZKAnQ/URqvGRqjYkI/AAAAAAAAAbs/42nyADFsXag/s160-c/The%252520Fisherman.jpg",  

  93.             "https://lh4.googleusercontent.com/-iLyZlzfdy7s/URqvG0YScdI/AAAAAAAAAbs/1J9eDKmkXtk/s160-c/The%252520Night%252520is%252520Coming.jpg",  

  94.             "https://lh6.googleusercontent.com/-G-k7YkkUco0/URqvHhah6fI/AAAAAAAAAbs/_taQQG7t0vo/s160-c/The%252520Road.jpg",  

  95.             "https://lh6.googleusercontent.com/-h-ALJt7kSus/URqvIThqYfI/AAAAAAAAAbs/ejiv35olWS8/s160-c/Tokyo%252520Heights.jpg",  

  96.             "https://lh5.googleusercontent.com/-Hy9k-TbS7xg/URqvIjQMOxI/AAAAAAAAAbs/RSpmmOATSkg/s160-c/Tokyo%252520Highway.jpg",  

  97.             "https://lh6.googleusercontent.com/-83oOvMb4OZs/URqvJL0T7lI/AAAAAAAAAbs/c5TECZ6RONM/s160-c/Tokyo%252520Smog.jpg",  

  98.             "https://lh3.googleusercontent.com/-FB-jfgREEfI/URqvJI3EXAI/AAAAAAAAAbs/XfyweiRF4v8/s160-c/Tufa%252520at%252520Night.jpg",  

  99.             "https://lh4.googleusercontent.com/-vngKD5Z1U8w/URqvJUCEgPI/AAAAAAAAAbs/ulxCMVcU6EU/s160-c/Valley%252520Sunset.jpg",  

  100.             "https://lh6.googleusercontent.com/-DOz5I2E2oMQ/URqvKMND1kI/AAAAAAAAAbs/Iqf0IsInleo/s160-c/Windmill%252520Sunrise.jpg",  

  101.             "https://lh5.googleusercontent.com/-biyiyWcJ9MU/URqvKculiAI/AAAAAAAAAbs/jyPsCplJOpE/s160-c/Windmill.jpg",  

  102.             "https://lh4.googleusercontent.com/-PDT167_xRdA/URqvK36mLcI/AAAAAAAAAbs/oi2ik9QseMI/s160-c/Windmills.jpg",  

  103.             "https://lh5.googleusercontent.com/-kI_QdYx7VlU/URqvLXCB6gI/AAAAAAAAAbs/N31vlZ6u89o/s160-c/Yet%252520Another%252520Rockaway%252520Sunset.jpg",  

  104.             "https://lh4.googleusercontent.com/-e9NHZ5k5MSs/URqvMIBZjtI/AAAAAAAAAbs/1fV810rDNfQ/s160-c/Yosemite%252520Tree.jpg", };  

  105.       

  106. }<span style="font-family:Times New Roman;font-size:14px;">  

  107. </span>  

  • ImageDownLoader類,異步下載的核心類,保存圖片到手機緩存,將圖片加入LruCache中等等

[java] view plaincopy在CODE上查看代碼片派生到個人代碼片

  1. package com.example.asyncimageloader;  

  2.   

  3. import java.io.IOException;  

  4. import java.net.HttpURLConnection;  

  5. import java.net.URL;  

  6. import java.util.concurrent.ExecutorService;  

  7. import java.util.concurrent.Executors;  

  8.   

  9. import android.content.Context;  

  10. import android.graphics.Bitmap;  

  11. import android.graphics.BitmapFactory;  

  12. import android.os.Handler;  

  13. import android.os.Message;  

  14. import android.support.v4.util.LruCache;  

  15.   

  16. public class ImageDownLoader {  

  17.     /** 

  18.      * 緩存Image的類,當存儲Image的大小大於LruCache設定的值,系統自動釋放內存 

  19.      */  

  20.     private LruCache<String, Bitmap> mMemoryCache;  

  21.     /** 

  22.      * 操做文件相關類對象的引用 

  23.      */  

  24.     private FileUtils fileUtils;  

  25.     /** 

  26.      * 下載Image的線程池 

  27.      */  

  28.     private ExecutorService mImageThreadPool = null;  

  29.       

  30.       

  31.     public ImageDownLoader(Context context){  

  32.         //獲取系統分配給每一個應用程序的最大內存,每一個應用系統分配32M  

  33.         int maxMemory = (int) Runtime.getRuntime().maxMemory();    

  34.         int mCacheSize = maxMemory / 8;  

  35.         //給LruCache分配1/8 4M  

  36.         mMemoryCache = new LruCache<String, Bitmap>(mCacheSize){  

  37.   

  38.             //必須重寫此方法,來測量Bitmap的大小  

  39.             @Override  

  40.             protected int sizeOf(String key, Bitmap value) {  

  41.                 return value.getRowBytes() * value.getHeight();  

  42.             }  

  43.               

  44.         };  

  45.           

  46.         fileUtils = new FileUtils(context);  

  47.     }  

  48.       

  49.       

  50.     /** 

  51.      * 獲取線程池的方法,由於涉及到併發的問題,咱們加上同步鎖 

  52.      * @return 

  53.      */  

  54.     public ExecutorService getThreadPool(){  

  55.         if(mImageThreadPool == null){  

  56.             synchronized(ExecutorService.class){  

  57.                 if(mImageThreadPool == null){  

  58.                     //爲了下載圖片更加的流暢,咱們用了2個線程來下載圖片  

  59.                     mImageThreadPool = Executors.newFixedThreadPool(2);  

  60.                 }  

  61.             }  

  62.         }  

  63.           

  64.         return mImageThreadPool;  

  65.           

  66.     }  

  67.       

  68.     /** 

  69.      * 添加Bitmap到內存緩存 

  70.      * @param key 

  71.      * @param bitmap 

  72.      */  

  73.     public void addBitmapToMemoryCache(String key, Bitmap bitmap) {    

  74.         if (getBitmapFromMemCache(key) == null && bitmap != null) {    

  75.             mMemoryCache.put(key, bitmap);    

  76.         }    

  77.     }    

  78.        

  79.     /** 

  80.      * 從內存緩存中獲取一個Bitmap 

  81.      * @param key 

  82.      * @return 

  83.      */  

  84.     public Bitmap getBitmapFromMemCache(String key) {    

  85.         return mMemoryCache.get(key);    

  86.     }   

  87.       

  88.     /** 

  89.      * 先從內存緩存中獲取Bitmap,若是沒有就從SD卡或者手機緩存中獲取,SD卡或者手機緩存 

  90.      * 沒有就去下載 

  91.      * @param url 

  92.      * @param listener 

  93.      * @return 

  94.      */  

  95.     public Bitmap downloadImage(final String url, final onImageLoaderListener listener){  

  96.         //替換Url中非字母和非數字的字符,這裏比較重要,由於咱們用Url做爲文件名,好比咱們的Url  

  97.         //是Http://xiaanming/abc.jpg;用這個做爲圖片名稱,系統會認爲xiaanming爲一個目錄,  

  98.         //咱們沒有建立此目錄保存文件就會報錯  

  99.         final String subUrl = url.replaceAll("[^\\w]""");  

  100.         Bitmap bitmap = showCacheBitmap(subUrl);  

  101.         if(bitmap != null){  

  102.             return bitmap;  

  103.         }else{  

  104.               

  105.             final Handler handler = new Handler(){  

  106.                 @Override  

  107.                 public void handleMessage(Message msg) {  

  108.                     super.handleMessage(msg);  

  109.                     listener.onImageLoader((Bitmap)msg.obj, url);  

  110.                 }  

  111.             };  

  112.               

  113.             getThreadPool().execute(new Runnable() {  

  114.                   

  115.                 @Override  

  116.                 public void run() {  

  117.                     Bitmap bitmap = getBitmapFormUrl(url);  

  118.                     Message msg = handler.obtainMessage();  

  119.                     msg.obj = bitmap;  

  120.                     handler.sendMessage(msg);  

  121.                       

  122.                     try {  

  123.                         //保存在SD卡或者手機目錄  

  124.                         fileUtils.savaBitmap(subUrl, bitmap);  

  125.                     } catch (IOException e) {  

  126.                         e.printStackTrace();  

  127.                     }  

  128.                       

  129.                     //將Bitmap 加入內存緩存  

  130.                     addBitmapToMemoryCache(subUrl, bitmap);  

  131.                 }  

  132.             });  

  133.         }  

  134.           

  135.         return null;  

  136.     }  

  137.       

  138.     /** 

  139.      * 獲取Bitmap, 內存中沒有就去手機或者sd卡中獲取,這一步在getView中會調用,比較關鍵的一步 

  140.      * @param url 

  141.      * @return 

  142.      */  

  143.     public Bitmap showCacheBitmap(String url){  

  144.         if(getBitmapFromMemCache(url) != null){  

  145.             return getBitmapFromMemCache(url);  

  146.         }else if(fileUtils.isFileExists(url) && fileUtils.getFileSize(url) != 0){  

  147.             //從SD卡獲取手機裏面獲取Bitmap  

  148.             Bitmap bitmap = fileUtils.getBitmap(url);  

  149.               

  150.             //將Bitmap 加入內存緩存  

  151.             addBitmapToMemoryCache(url, bitmap);  

  152.             return bitmap;  

  153.         }  

  154.           

  155.         return null;  

  156.     }  

  157.       

  158.       

  159.     /** 

  160.      * 從Url中獲取Bitmap 

  161.      * @param url 

  162.      * @return 

  163.      */  

  164.     private Bitmap getBitmapFormUrl(String url) {  

  165.         Bitmap bitmap = null;  

  166.         HttpURLConnection con = null;  

  167.         try {  

  168.             URL mImageUrl = new URL(url);  

  169.             con = (HttpURLConnection) mImageUrl.openConnection();  

  170.             con.setConnectTimeout(10 * 1000);  

  171.             con.setReadTimeout(10 * 1000);  

  172.             con.setDoInput(true);  

  173.             con.setDoOutput(true);  

  174.             bitmap = BitmapFactory.decodeStream(con.getInputStream());  

  175.         } catch (Exception e) {  

  176.             e.printStackTrace();  

  177.         } finally {  

  178.             if (con != null) {  

  179.                 con.disconnect();  

  180.             }  

  181.         }  

  182.         return bitmap;  

  183.     }  

  184.       

  185.     /** 

  186.      * 取消正在下載的任務 

  187.      */  

  188.     public synchronized void cancelTask() {  

  189.         if(mImageThreadPool != null){  

  190.             mImageThreadPool.shutdownNow();  

  191.             mImageThreadPool = null;  

  192.         }  

  193.     }  

  194.       

  195.       

  196.     /** 

  197.      * 異步下載圖片的回調接口 

  198.      * @author len 

  199.      * 

  200.      */  

  201.     public interface onImageLoaderListener{  

  202.         void onImageLoader(Bitmap bitmap, String url);  

  203.     }  

  204.       

  205. }  

ImageDownLoader中有幾個方法比較重要

  1. 首先咱們須要重寫sizeOf(String key, Bitmap value)來計算圖片的大小,默認返回圖片的數量

  2. downloadImage(final String url, final onImageLoaderListener listener)先去LruCache查看Image,沒有再去手機緩存中查看,在沒有則開啓線程下載,這裏咱們提供了一個回調接口,回調方法中咱們將Bitmap和圖片Url做爲參數,String subUrl = url.replaceAll("[^\\w]", "") 我在代碼中註釋寫的比較清楚

  3. showCacheBitmap(String url)方法,此方法在Adapter中的getView()當中調用,若是getView()中不調用此方法試試你就知道效果了


  • ImageAdapter  GridView的適配器類,主要是GridView滑動的時候取消下載任務,靜止的時候去下載當前顯示的item的圖片,其餘也沒什麼不一樣了

[java] view plaincopy在CODE上查看代碼片派生到個人代碼片

  1. package com.example.asyncimageloader;  

  2.   

  3. import android.content.Context;  

  4. import android.graphics.Bitmap;  

  5. import android.view.View;  

  6. import android.view.ViewGroup;  

  7. import android.widget.AbsListView;  

  8. import android.widget.AbsListView.OnScrollListener;  

  9. import android.widget.BaseAdapter;  

  10. import android.widget.GridView;  

  11. import android.widget.ImageView;  

  12.   

  13. import com.example.asyncimageloader.ImageDownLoader.onImageLoaderListener;  

  14.   

  15. public class ImageAdapter extends BaseAdapter implements OnScrollListener{  

  16.     /** 

  17.      * 上下文對象的引用 

  18.      */  

  19.     private Context context;  

  20.       

  21.     /** 

  22.      * Image Url的數組 

  23.      */  

  24.     private String [] imageThumbUrls;  

  25.       

  26.     /** 

  27.      * GridView對象的應用 

  28.      */  

  29.     private GridView mGridView;  

  30.       

  31.     /** 

  32.      * Image 下載器 

  33.      */  

  34.     private ImageDownLoader mImageDownLoader;  

  35.       

  36.     /** 

  37.      * 記錄是否剛打開程序,用於解決進入程序不滾動屏幕,不會下載圖片的問題。 

  38.      * 參考http://blog.csdn.net/guolin_blog/article/details/9526203#comments 

  39.      */  

  40.     private boolean isFirstEnter = true;  

  41.       

  42.     /** 

  43.      * 一屏中第一個item的位置 

  44.      */  

  45.     private int mFirstVisibleItem;  

  46.       

  47.     /** 

  48.      * 一屏中全部item的個數 

  49.      */  

  50.     private int mVisibleItemCount;  

  51.       

  52.       

  53.     public ImageAdapter(Context context, GridView mGridView, String [] imageThumbUrls){  

  54.         this.context = context;  

  55.         this.mGridView = mGridView;  

  56.         this.imageThumbUrls = imageThumbUrls;  

  57.         mImageDownLoader = new ImageDownLoader(context);  

  58.         mGridView.setOnScrollListener(this);  

  59.     }  

  60.       

  61.     @Override  

  62.     public void onScrollStateChanged(AbsListView view, int scrollState) {  

  63.         //僅當GridView靜止時纔去下載圖片,GridView滑動時取消全部正在下載的任務    

  64.         if(scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE){  

  65.             showImage(mFirstVisibleItem, mVisibleItemCount);  

  66.         }else{  

  67.             cancelTask();  

  68.         }  

  69.           

  70.     }  

  71.   

  72.   

  73.     /** 

  74.      * GridView滾動的時候調用的方法,剛開始顯示GridView也會調用此方法 

  75.      */  

  76.     @Override  

  77.     public void onScroll(AbsListView view, int firstVisibleItem,  

  78.             int visibleItemCount, int totalItemCount) {  

  79.         mFirstVisibleItem = firstVisibleItem;  

  80.         mVisibleItemCount = visibleItemCount;  

  81.         // 所以在這裏爲首次進入程序開啓下載任務。   

  82.         if(isFirstEnter && visibleItemCount > 0){  

  83.             showImage(mFirstVisibleItem, mVisibleItemCount);  

  84.             isFirstEnter = false;  

  85.         }  

  86.     }  

  87.       

  88.   

  89.     @Override  

  90.     public int getCount() {  

  91.         return imageThumbUrls.length;  

  92.     }  

  93.   

  94.     @Override  

  95.     public Object getItem(int position) {  

  96.         return imageThumbUrls[position];  

  97.     }  

  98.   

  99.     @Override  

  100.     public long getItemId(int position) {  

  101.         return position;  

  102.     }  

  103.   

  104.     @Override  

  105.     public View getView(int position, View convertView, ViewGroup parent) {  

  106.         ImageView mImageView;  

  107.         final String mImageUrl = imageThumbUrls[position];  

  108.         if(convertView == null){  

  109.             mImageView = new ImageView(context);  

  110.         }else{  

  111.             mImageView = (ImageView) convertView;  

  112.         }  

  113.           

  114.         mImageView.setLayoutParams(new GridView.LayoutParams(150150));  

  115.         mImageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);  

  116.           

  117.         //給ImageView設置Tag,這裏已是司空見慣了  

  118.         mImageView.setTag(mImageUrl);  

  119.           

  120.           

  121.         /*******************************去掉下面這幾行試試是什麼效果****************************/  

  122.         Bitmap bitmap = mImageDownLoader.showCacheBitmap(mImageUrl.replaceAll("[^\\w]"""));  

  123.         if(bitmap != null){  

  124.             mImageView.setImageBitmap(bitmap);  

  125.         }else{  

  126.             mImageView.setImageDrawable(context.getResources().getDrawable(R.drawable.ic_empty));  

  127.         }  

  128.         /**********************************************************************************/  

  129.           

  130.           

  131.         return mImageView;  

  132.     }  

  133.       

  134.     /** 

  135.      * 顯示當前屏幕的圖片,先會去查找LruCache,LruCache沒有就去sd卡或者手機目錄查找,在沒有就開啓線程去下載 

  136.      * @param firstVisibleItem 

  137.      * @param visibleItemCount 

  138.      */  

  139.     private void showImage(int firstVisibleItem, int visibleItemCount){  

  140.         Bitmap bitmap = null;  

  141.         for(int i=firstVisibleItem; i<firstVisibleItem + visibleItemCount; i++){  

  142.             String mImageUrl = imageThumbUrls[i];  

  143.             final ImageView mImageView = (ImageView) mGridView.findViewWithTag(mImageUrl);  

  144.             bitmap = mImageDownLoader.downloadImage(mImageUrl, new onImageLoaderListener() {  

  145.                   

  146.                 @Override  

  147.                 public void onImageLoader(Bitmap bitmap, String url) {  

  148.                     if(mImageView != null && bitmap != null){  

  149.                         mImageView.setImageBitmap(bitmap);  

  150.                     }  

  151.                       

  152.                 }  

  153.             });  

  154.               

  155.             //if(bitmap != null){  

  156.             //  mImageView.setImageBitmap(bitmap);  

  157.             //}else{  

  158.             //  mImageView.setImageDrawable(context.getResources().getDrawable(R.drawable.ic_empty));  

  159.             //}  

  160.         }  

  161.     }  

  162.   

  163.     /** 

  164.      * 取消下載任務 

  165.      */  

  166.     public void cancelTask(){  

  167.         mImageDownLoader.cancelTask();  

  168.     }  

  169.   

  170.   

  171. }  

  • MainActivity  裏面一個GridView,而後提供一個系統菜單來刪除手機上的緩存圖片,直接上代碼,比較簡單因此裏面也沒有註釋

[java] view plaincopy在CODE上查看代碼片派生到個人代碼片

  1. package com.example.asyncimageloader;  

  2.   

  3. import android.app.Activity;  

  4. import android.os.Bundle;  

  5. import android.view.Menu;  

  6. import android.view.MenuItem;  

  7. import android.widget.GridView;  

  8. import android.widget.Toast;  

  9.   

  10. public class MainActivity extends Activity {  

  11.     private GridView mGridView;  

  12.     private String [] imageThumbUrls = Images.imageThumbUrls;   

  13.     private ImageAdapter mImageAdapter;  

  14.     private FileUtils fileUtils;  

  15.   

  16.     @Override  

  17.     protected void onCreate(Bundle savedInstanceState) {  

  18.         super.onCreate(savedInstanceState);  

  19.         setContentView(R.layout.activity_main);  

  20.         fileUtils = new FileUtils(this);  

  21.         mGridView = (GridView) findViewById(R.id.gridView);  

  22.         mImageAdapter = new ImageAdapter(this, mGridView, imageThumbUrls);  

  23.         mGridView.setAdapter(mImageAdapter);  

  24.     }  

  25.   

  26.     @Override  

  27.     protected void onDestroy() {  

  28.         mImageAdapter.cancelTask();  

  29.         super.onDestroy();  

  30.     }  

  31.   

  32.     @Override  

  33.     public boolean onCreateOptionsMenu(Menu menu) {  

  34.         super.onCreateOptionsMenu(menu);  

  35.         menu.add("刪除手機中圖片緩存");  

  36.         return super.onCreateOptionsMenu(menu);  

  37.     }  

  38.   

  39.     @Override  

  40.     public boolean onOptionsItemSelected(MenuItem item) {  

  41.         switch (item.getItemId()) {  

  42.         case 0:  

  43.             fileUtils.deleteFile();  

  44.             Toast.makeText(getApplication(), "清空緩存成功", Toast.LENGTH_SHORT).show();  

  45.             break;  

  46.         }  

  47.         return super.onOptionsItemSelected(item);  

  48.     }  

  49.   

  50. }<span style="font-family:Times New Roman;font-size:14px;">  

  51. </span>  

  • MainActivity的佈局文件

[html] view plaincopy在CODE上查看代碼片派生到個人代碼片

  1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  

  2.     xmlns:tools="http://schemas.android.com/tools"  

  3.     android:layout_width="match_parent"  

  4.     android:layout_height="match_parent"  

  5.     tools:context=".MainActivity" >  

  6.   

  7.     <GridView  

  8.         android:id="@+id/gridView"  

  9.         android:layout_width="match_parent"  

  10.         android:layout_height="match_parent"  

  11.         android:stretchMode="columnWidth"   

  12.         android:columnWidth="90dip"   

  13.         android:verticalSpacing="10dip"  

  14.         android:horizontalSpacing="10dip"  

  15.         android:cacheColorHint="@android:color/transparent"  

  16.         android:numColumns="auto_fit" >  

  17.     </GridView>  

  18.   

  19. </RelativeLayout>  

  • 由於有網絡操做和對sd卡的操做,因此咱們必須加上相對應的權限

[html] view plaincopy在CODE上查看代碼片派生到個人代碼片

  1. <uses-permission android:name="android.permission.INTERNET" />   

  2. <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />   

好了,代碼就所有介紹完了,咱們運行下程序看看效果,這裏的效果是用一個線程下載圖片的效果,可能有一些不完整,想看看效果本身動手試試,鬱悶,家裏的網絡卡,gif的圖片出不來效果,只能明天上傳圖片啦,公司也上傳不了動畫效果,我去,那我就貼一張普通圖片,哈哈




好了,今天的講解到此結束,有疑問的朋友請在下面留言,源碼裏面GridView的佈局文件 columnWedth設置了120dip,有點醜,你們能夠改爲90dip

相關文章
相關標籤/搜索