編輯:Android開發實例
異步加載圖片的例子,網上也比較多,大部分用了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包(這裡要注意咯)
為什麼寫這篇文章呢?
因為我之前做的項目中,也有異步加載圖片,那時候用得是Thread去下載圖片,每次下載圖片都要new Thread去下載,而且還是並發去下載,每次都new 一個線程浪費內存,老板說服務器承受不起這麼多的連接,叫我改成先獲取一張圖片之後再去獲取下一張,這樣子保存與服務器的連接為一個,服務器壓力小了,然後樓主就想到線程池,線程池很好的幫我們管理並發的問題,並發的問題解決了,可是後面又出問題了,圖片多了就出現OOM(OutOfMemory)異常,之後用了SoftReference,先用SoftReference中獲取圖片,SoftReference沒有就開線程去下載,老板說你為什麼不把圖片在手機上做個緩存呢,於是我用了手機緩存,大概思路就是先從SoftReference中獲取圖片,如果SoftReference沒有就去手機緩存中獲取,手機緩存中沒有就開啟先從去下載,然後成功的解決了OOM的問題,前些天老板要我重構下代碼,我也覺得之前寫的代碼耦合性太強,早就想改,然後之前http://www.fengfly.com/plus/view-214547-1.html這篇文章,LruCache和滑動過程中取消下載任務,停下來的時候才去下載這2點比較好,值得我學習,然後我就將我的項目異步加載這一塊改了下,發到這裡做個記錄吧,以後類似的異步加載圖片直接拷貝代碼,提交開發的效率
這篇文章做了哪些方面的優化
使用了線程池來管理下載任務
使用LruCache來緩存圖片
使用手機來緩存圖片
GridView滑動的時候取消下載任務,靜止的時候進行下載,GridView滑動更加的流暢
降低了代碼的耦合性,結構更加的清晰,便於以後重用
接下來我們先來看看項目的結構
FileUtils 文件操作的工具類,提供保存圖片,獲取圖片,判斷圖片是否存在,刪除圖片的一些方法,這個類比較簡單
- package com.example.asyncimageloader;
- import java.io.File;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import android.content.Context;
- import android.graphics.Bitmap;
- import android.graphics.Bitmap.CompressFormat;
- import android.graphics.BitmapFactory;
- import android.os.Environment;
- public class FileUtils {
- /**
- * sd卡的根目錄
- */
- private static String mSdRootPath = Environment.getExternalStorageDirectory().getPath();
- /**
- * 手機的緩存根目錄
- */
- private static String mDataRootPath = null;
- /**
- * 保存Image的目錄名
- */
- private final static String FOLDER_NAME = "/AndroidImage";
- public FileUtils(Context context){
- mDataRootPath = context.getCacheDir().getPath();
- }
- /**
- * 獲取儲存Image的目錄
- * @return
- */
- private String getStorageDirectory(){
- return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED) ?
- mSdRootPath + FOLDER_NAME : mDataRootPath + FOLDER_NAME;
- }
- /**
- * 保存Image的方法,有sd卡存儲到sd卡,沒有就存儲到手機目錄
- * @param fileName
- * @param bitmap
- * @throws IOException
- */
- public void savaBitmap(String fileName, Bitmap bitmap) throws IOException{
- if(bitmap == null){
- return;
- }
- String path = getStorageDirectory();
- File folderFile = new File(path);
- if(!folderFile.exists()){
- folderFile.mkdir();
- }
- File file = new File(path + File.separator + fileName);
- file.createNewFile();
- FileOutputStream fos = new FileOutputStream(file);
- bitmap.compress(CompressFormat.JPEG, 100, fos);
- fos.flush();
- fos.close();
- }
- /**
- * 從手機或者sd卡獲取Bitmap
- * @param fileName
- * @return
- */
- public Bitmap getBitmap(String fileName){
- return BitmapFactory.decodeFile(getStorageDirectory() + File.separator + fileName);
- }
- /**
- * 判斷文件是否存在
- * @param fileName
- * @return
- */
- public boolean isFileExists(String fileName){
- return new File(getStorageDirectory() + File.separator + fileName).exists();
- }
- /**
- * 獲取文件的大小
- * @param fileName
- * @return
- */
- public long getFileSize(String fileName) {
- return new File(getStorageDirectory() + File.separator + fileName).length();
- }
- /**
- * 刪除SD卡或者手機的緩存圖片和目錄
- */
- public void deleteFile() {
- File dirFile = new File(getStorageDirectory());
- if(! dirFile.exists()){
- return;
- }
- if (dirFile.isDirectory()) {
- String[] children = dirFile.list();
- for (int i = 0; i < children.length; i++) {
- new File(dirFile, children[i]).delete();
- }
- }
- dirFile.delete();
- }
- }
Images類,提供圖片資源的類,來自Android文檔中BitmapFun中http://developer.android.com/training/displaying-bitmaps/index.html,裡面一個靜態的圖片Url數組,這裡面比較坑爹,因為是圖片是google官網提供的,有時候會下載超時
- package com.example.asyncimageloader;
- public class Images {
- public final static String[] imageThumbUrls = new String[] {
- "https://lh6.googleusercontent.com/-55osAWw3x0Q/URquUtcFr5I/AAAAAAAAAbs/rWlj1RUKrYI/s160-c/A%252520Photographer.jpg",
- "https://lh4.googleusercontent.com/--dq8niRp7W4/URquVgmXvgI/AAAAAAAAAbs/-gnuLQfNnBA/s160-c/A%252520Song%252520of%252520Ice%252520and%252520Fire.jpg",
- "https://lh5.googleusercontent.com/-7qZeDtRKFKc/URquWZT1gOI/AAAAAAAAAbs/hqWgteyNXsg/s160-c/Another%252520Rockaway%252520Sunset.jpg",
- "https://lh3.googleusercontent.com/--L0Km39l5J8/URquXHGcdNI/AAAAAAAAAbs/3ZrSJNrSomQ/s160-c/Antelope%252520Butte.jpg",
- "https://lh6.googleusercontent.com/-8HO-4vIFnlw/URquZnsFgtI/AAAAAAAAAbs/WT8jViTF7vw/s160-c/Antelope%252520Hallway.jpg",
- "https://lh4.googleusercontent.com/-WIuWgVcU3Qw/URqubRVcj4I/AAAAAAAAAbs/YvbwgGjwdIQ/s160-c/Antelope%252520Walls.jpg",
- "https://lh6.googleusercontent.com/-UBmLbPELvoQ/URqucCdv0kI/AAAAAAAAAbs/IdNhr2VQoQs/s160-c/Apre%2525CC%252580s%252520la%252520Pluie.jpg",
- "https://lh3.googleusercontent.com/-s-AFpvgSeew/URquc6dF-JI/AAAAAAAAAbs/Mt3xNGRUd68/s160-c/Backlit%252520Cloud.jpg",
- "https://lh5.googleusercontent.com/-bvmif9a9YOQ/URquea3heHI/AAAAAAAAAbs/rcr6wyeQtAo/s160-c/Bee%252520and%252520Flower.jpg",
- "https://lh5.googleusercontent.com/-n7mdm7I7FGs/URqueT_BT-I/AAAAAAAAAbs/9MYmXlmpSAo/s160-c/Bonzai%252520Rock%252520Sunset.jpg",
- "https://lh6.googleusercontent.com/-4CN4X4t0M1k/URqufPozWzI/AAAAAAAAAbs/8wK41lg1KPs/s160-c/Caterpillar.jpg",
- "https://lh3.googleusercontent.com/-rrFnVC8xQEg/URqufdrLBaI/AAAAAAAAAbs/s69WYy_fl1E/s160-c/Chess.jpg",
- "https://lh5.googleusercontent.com/-WVpRptWH8Yw/URqugh-QmDI/AAAAAAAAAbs/E-MgBgtlUWU/s160-c/Chihuly.jpg",
- "https://lh5.googleusercontent.com/-0BDXkYmckbo/URquhKFW84I/AAAAAAAAAbs/ogQtHCTk2JQ/s160-c/Closed%252520Door.jpg",
- "https://lh3.googleusercontent.com/-PyggXXZRykM/URquh-kVvoI/AAAAAAAAAbs/hFtDwhtrHHQ/s160-c/Colorado%252520River%252520Sunset.jpg",
- "https://lh3.googleusercontent.com/-ZAs4dNZtALc/URquikvOCWI/AAAAAAAAAbs/DXz4h3dll1Y/s160-c/Colors%252520of%252520Autumn.jpg",
- "https://lh4.googleusercontent.com/-GztnWEIiMz8/URqukVCU7bI/AAAAAAAAAbs/jo2Hjv6MZ6M/s160-c/Countryside.jpg",
- "https://lh4.googleusercontent.com/-bEg9EZ9QoiM/URquklz3FGI/AAAAAAAAAbs/UUuv8Ac2BaE/s160-c/Death%252520Valley%252520-%252520Dunes.jpg",
- "https://lh6.googleusercontent.com/-ijQJ8W68tEE/URqulGkvFEI/AAAAAAAAAbs/zPXvIwi_rFw/s160-c/Delicate%252520Arch.jpg",
- "https://lh5.googleusercontent.com/-Oh8mMy2ieng/URqullDwehI/AAAAAAAAAbs/TbdeEfsaIZY/s160-c/Despair.jpg",
- "https://lh5.googleusercontent.com/-gl0y4UiAOlk/URqumC_KjBI/AAAAAAAAAbs/PM1eT7dn4oo/s160-c/Eagle%252520Fall%252520Sunrise.jpg",
- "https://lh3.googleusercontent.com/-hYYHd2_vXPQ/URqumtJa9eI/AAAAAAAAAbs/wAalXVkbSh0/s160-c/Electric%252520Storm.jpg",
- "https://lh5.googleusercontent.com/-PyY_yiyjPTo/URqunUOhHFI/AAAAAAAAAbs/azZoULNuJXc/s160-c/False%252520Kiva.jpg",
- "https://lh6.googleusercontent.com/-PYvLVdvXywk/URqunwd8hfI/AAAAAAAAAbs/qiMwgkFvf6I/s160-c/Fitzgerald%252520Streaks.jpg",
- "https://lh4.googleusercontent.com/-KIR_UobIIqY/URquoCZ9SlI/AAAAAAAAAbs/Y4d4q8sXu4c/s160-c/Foggy%252520Sunset.jpg",
- "https://lh6.googleusercontent.com/-9lzOk_OWZH0/URquoo4xYoI/AAAAAAAAAbs/AwgzHtNVCwU/s160-c/Frantic.jpg",
- "https://lh3.googleusercontent.com/-0X3JNaKaz48/URqupH78wpI/AAAAAAAAAbs/lHXxu_zbH8s/s160-c/Golden%252520Gate%252520Afternoon.jpg",
- "https://lh6.googleusercontent.com/-95sb5ag7ABc/URqupl95RDI/AAAAAAAAAbs/g73R20iVTRA/s160-c/Golden%252520Gate%252520Fog.jpg",
- "https://lh3.googleusercontent.com/-JB9v6rtgHhk/URqup21F-zI/AAAAAAAAAbs/64Fb8qMZWXk/s160-c/Golden%252520Grass.jpg",
- "https://lh4.googleusercontent.com/-EIBGfnuLtII/URquqVHwaRI/AAAAAAAAAbs/FA4McV2u8VE/s160-c/Grand%252520Teton.jpg",
- "https://lh4.googleusercontent.com/-WoMxZvmN9nY/URquq1v2AoI/AAAAAAAAAbs/grj5uMhL6NA/s160-c/Grass%252520Closeup.jpg",
- "https://lh3.googleusercontent.com/-6hZiEHXx64Q/URqurxvNdqI/AAAAAAAAAbs/kWMXM3o5OVI/s160-c/Green%252520Grass.jpg",
- "https://lh5.googleusercontent.com/-6LVb9OXtQ60/URquteBFuKI/AAAAAAAAAbs/4F4kRgecwFs/s160-c/Hanging%252520Leaf.jpg",
- "https://lh4.googleusercontent.com/-zAvf__52ONk/URqutT_IuxI/AAAAAAAAAbs/D_bcuc0thoU/s160-c/Highway%2525201.jpg",
- "https://lh6.googleusercontent.com/-H4SrUg615rA/URquuL27fXI/AAAAAAAAAbs/4aEqJfiMsOU/s160-c/Horseshoe%252520Bend%252520Sunset.jpg",
- "https://lh4.googleusercontent.com/-JhFi4fb_Pqw/URquuX-QXbI/AAAAAAAAAbs/IXpYUxuweYM/s160-c/Horseshoe%252520Bend.jpg",
- "https://lh5.googleusercontent.com/-UGgssvFRJ7g/URquueyJzGI/AAAAAAAAAbs/yYIBlLT0toM/s160-c/Into%252520the%252520Blue.jpg",
- "https://lh3.googleusercontent.com/-CH7KoupI7uI/URquu0FF__I/AAAAAAAAAbs/R7GDmI7v_G0/s160-c/Jelly%252520Fish%2525202.jpg",
- "https://lh4.googleusercontent.com/-pwuuw6yhg8U/URquvPxR3FI/AAAAAAAAAbs/VNGk6f-tsGE/s160-c/Jelly%252520Fish%2525203.jpg",
- "https://lh5.googleusercontent.com/-GoUQVw1fnFw/URquv6xbC0I/AAAAAAAAAbs/zEUVTQQ43Zc/s160-c/Kauai.jpg",
- "https://lh6.googleusercontent.com/-8QdYYQEpYjw/URquwvdh88I/AAAAAAAAAbs/cktDy-ysfHo/s160-c/Kyoto%252520Sunset.jpg",
- "https://lh4.googleusercontent.com/-vPeekyDjOE0/URquwzJ28qI/AAAAAAAAAbs/qxcyXULsZrg/s160-c/Lake%252520Tahoe%252520Colors.jpg",
- "https://lh4.googleusercontent.com/-xBPxWpD4yxU/URquxWHk8AI/AAAAAAAAAbs/ARDPeDYPiMY/s160-c/Lava%252520from%252520the%252520Sky.jpg",
- "https://lh3.googleusercontent.com/-897VXrJB6RE/URquxxxd-5I/AAAAAAAAAbs/j-Cz4T4YvIw/s160-c/Leica%25252050mm%252520Summilux.jpg",
- "https://lh5.googleusercontent.com/-qSJ4D4iXzGo/URquyDWiJ1I/AAAAAAAAAbs/k2pBXeWehOA/s160-c/Leica%25252050mm%252520Summilux.jpg",
- "https://lh6.googleusercontent.com/-dwlPg83vzLg/URquylTVuFI/AAAAAAAAAbs/G6SyQ8b4YsI/s160-c/Leica%252520M8%252520%252528Front%252529.jpg",
- "https://lh3.googleusercontent.com/-R3_EYAyJvfk/URquzQBv8eI/AAAAAAAAAbs/b9xhpUM3pEI/s160-c/Light%252520to%252520Sand.jpg",
- "https://lh3.googleusercontent.com/-fHY5h67QPi0/URqu0Cp4J1I/AAAAAAAAAbs/0lG6m94Z6vM/s160-c/Little%252520Bit%252520of%252520Paradise.jpg",
- "https://lh5.googleusercontent.com/-TzF_LwrCnRM/URqu0RddPOI/AAAAAAAAAbs/gaj2dLiuX0s/s160-c/Lone%252520Pine%252520Sunset.jpg",
- "https://lh3.googleusercontent.com/-4HdpJ4_DXU4/URqu046dJ9I/AAAAAAAAAbs/eBOodtk2_uk/s160-c/Lonely%252520Rock.jpg",
- "https://lh6.googleusercontent.com/-erbF--z-W4s/URqu1ajSLkI/AAAAAAAAAbs/xjDCDO1INzM/s160-c/Longue%252520Vue.jpg",
- "https://lh6.googleusercontent.com/-0CXJRdJaqvc/URqu1opNZNI/AAAAAAAAAbs/PFB2oPUU7Lk/s160-c/Look%252520Me%252520in%252520the%252520Eye.jpg",
- "https://lh3.googleusercontent.com/-D_5lNxnDN6g/URqu2Tk7HVI/AAAAAAAAAbs/p0ddca9W__Y/s160-c/Lost%252520in%252520a%252520Field.jpg",
- "https://lh6.googleusercontent.com/-flsqwMrIk2Q/URqu24PcmjI/AAAAAAAAAbs/5ocIH85XofM/s160-c/Marshall%252520Beach%252520Sunset.jpg",
- "https://lh4.googleusercontent.com/-Y4lgryEVTmU/URqu28kG3gI/AAAAAAAAAbs/OjXpekqtbJ4/s160-c/Mono%252520Lake%252520Blue.jpg",
- "https://lh4.googleusercontent.com/-AaHAJPmcGYA/URqu3PIldHI/AAAAAAAAAbs/lcTqk1SIcRs/s160-c/Monument%252520Valley%252520Overlook.jpg",
- "https://lh4.googleusercontent.com/-vKxfdQ83dQA/URqu31Yq_BI/AAAAAAAAAbs/OUoGk_2AyfM/s160-c/Moving%252520Rock.jpg",
- "https://lh5.googleusercontent.com/-CG62QiPpWXg/URqu4ia4vRI/AAAAAAAAAbs/0YOdqLAlcAc/s160-c/Napali%252520Coast.jpg",
- "https://lh6.googleusercontent.com/-wdGrP5PMmJQ/URqu5PZvn7I/AAAAAAAAAbs/m0abEcdPXe4/s160-c/One%252520Wheel.jpg",
- "https://lh6.googleusercontent.com/-6WS5DoCGuOA/URqu5qx1UgI/AAAAAAAAAbs/giMw2ixPvrY/s160-c/Open%252520Sky.jpg",
- "https://lh6.googleusercontent.com/-u8EHKj8G8GQ/URqu55sM6yI/AAAAAAAAAbs/lIXX_GlTdmI/s160-c/Orange%252520Sunset.jpg",
- "https://lh6.googleusercontent.com/-74Z5qj4bTDE/URqu6LSrJrI/AAAAAAAAAbs/XzmVkw90szQ/s160-c/Orchid.jpg",
- "https://lh6.googleusercontent.com/-lEQE4h6TePE/URqu6t_lSkI/AAAAAAAAAbs/zvGYKOea_qY/s160-c/Over%252520there.jpg",
- "https://lh5.googleusercontent.com/-cauH-53JH2M/URqu66v_USI/AAAAAAAAAbs/EucwwqclfKQ/s160-c/Plumes.jpg",
- "https://lh3.googleusercontent.com/-eDLT2jHDoy4/URqu7axzkAI/AAAAAAAAAbs/iVZE-xJ7lZs/s160-c/Rainbokeh.jpg",
- "https://lh5.googleusercontent.com/-j1NLqEFIyco/URqu8L1CGcI/AAAAAAAAAbs/aqZkgX66zlI/s160-c/Rainbow.jpg",
- "https://lh5.googleusercontent.com/-DRnqmK0t4VU/URqu8XYN9yI/AAAAAAAAAbs/LgvF_592WLU/s160-c/Rice%252520Fields.jpg",
- "https://lh3.googleusercontent.com/-hwh1v3EOGcQ/URqu8qOaKwI/AAAAAAAAAbs/IljRJRnbJGw/s160-c/Rockaway%252520Fire%252520Sky.jpg",
- "https://lh5.googleusercontent.com/-wjV6FQk7tlk/URqu9jCQ8sI/AAAAAAAAAbs/RyYUpdo-c9o/s160-c/Rockaway%252520Flow.jpg",
- "https://lh6.googleusercontent.com/-6cAXNfo7D20/URqu-BdzgPI/AAAAAAAAAbs/OmsYllzJqwo/s160-c/Rockaway%252520Sunset%252520Sky.jpg",
- "https://lh3.googleusercontent.com/-sl8fpGPS-RE/URqu_BOkfgI/AAAAAAAAAbs/Dg2Fv-JxOeg/s160-c/Russian%252520Ridge%252520Sunset.jpg",
- "https://lh6.googleusercontent.com/-gVtY36mMBIg/URqu_q91lkI/AAAAAAAAAbs/3CiFMBcy5MA/s160-c/Rust%252520Knot.jpg",
- "https://lh6.googleusercontent.com/-GHeImuHqJBE/URqu_FKfVLI/AAAAAAAAAbs/axuEJeqam7Q/s160-c/Sailing%252520Stones.jpg",
- "https://lh3.googleusercontent.com/-hBbYZjTOwGc/URqu_ycpIrI/AAAAAAAAAbs/nAdJUXnGJYE/s160-c/Seahorse.jpg",
- "https://lh3.googleusercontent.com/-Iwi6-i6IexY/URqvAYZHsVI/AAAAAAAAAbs/5ETWl4qXsFE/s160-c/Shinjuku%252520Street.jpg",
- "https://lh6.googleusercontent.com/-amhnySTM_MY/URqvAlb5KoI/AAAAAAAAAbs/pFCFgzlKsn0/s160-c/Sierra%252520Heavens.jpg",
- "https://lh5.googleusercontent.com/-dJgjepFrYSo/URqvBVJZrAI/AAAAAAAAAbs/v-F5QWpYO6s/s160-c/Sierra%252520Sunset.jpg",
- "https://lh4.googleusercontent.com/-Z4zGiC5nWdc/URqvBdEwivI/AAAAAAAAAbs/ZRZR1VJ84QA/s160-c/Sin%252520Lights.jpg",
- "https://lh4.googleusercontent.com/-_0cYiWW8ccY/URqvBz3iM4I/AAAAAAAAAbs/9N_Wq8MhLTY/s160-c/Starry%252520Lake.jpg",
- "https://lh3.googleusercontent.com/-A9LMoRyuQUA/URqvCYx_JoI/AAAAAAAAAbs/s7sde1Bz9cI/s160-c/Starry%252520Night.jpg",
- "https://lh3.googleusercontent.com/-KtLJ3k858eY/URqvC_2h_bI/AAAAAAAAAbs/zzEBImwDA_g/s160-c/Stream.jpg",
- "https://lh5.googleusercontent.com/-dFB7Lad6RcA/URqvDUftwWI/AAAAAAAAAbs/BrhoUtXTN7o/s160-c/Strip%252520Sunset.jpg",
- "https://lh5.googleusercontent.com/-at6apgFiN20/URqvDyffUZI/AAAAAAAAAbs/clABCx171bE/s160-c/Sunset%252520Hills.jpg",
- "https://lh4.googleusercontent.com/-7-EHhtQthII/URqvEYTk4vI/AAAAAAAAAbs/QSJZoB3YjVg/s160-c/Tenaya%252520Lake%2525202.jpg",
- "https://lh6.googleusercontent.com/-8MrjV_a-Pok/URqvFC5repI/AAAAAAAAAbs/9inKTg9fbCE/s160-c/Tenaya%252520Lake.jpg",
- "https://lh5.googleusercontent.com/-B1HW-z4zwao/URqvFWYRwUI/AAAAAAAAAbs/8Peli53Bs8I/s160-c/The%252520Cave%252520BW.jpg",
- "https://lh3.googleusercontent.com/-PO4E-xZKAnQ/URqvGRqjYkI/AAAAAAAAAbs/42nyADFsXag/s160-c/The%252520Fisherman.jpg",
- "https://lh4.googleusercontent.com/-iLyZlzfdy7s/URqvG0YScdI/AAAAAAAAAbs/1J9eDKmkXtk/s160-c/The%252520Night%252520is%252520Coming.jpg",
- "https://lh6.googleusercontent.com/-G-k7YkkUco0/URqvHhah6fI/AAAAAAAAAbs/_taQQG7t0vo/s160-c/The%252520Road.jpg",
- "https://lh6.googleusercontent.com/-h-ALJt7kSus/URqvIThqYfI/AAAAAAAAAbs/ejiv35olWS8/s160-c/Tokyo%252520Heights.jpg",
- "https://lh5.googleusercontent.com/-Hy9k-TbS7xg/URqvIjQMOxI/AAAAAAAAAbs/RSpmmOATSkg/s160-c/Tokyo%252520Highway.jpg",
- "https://lh6.googleusercontent.com/-83oOvMb4OZs/URqvJL0T7lI/AAAAAAAAAbs/c5TECZ6RONM/s160-c/Tokyo%252520Smog.jpg",
- "https://lh3.googleusercontent.com/-FB-jfgREEfI/URqvJI3EXAI/AAAAAAAAAbs/XfyweiRF4v8/s160-c/Tufa%252520at%252520Night.jpg",
- "https://lh4.googleusercontent.com/-vngKD5Z1U8w/URqvJUCEgPI/AAAAAAAAAbs/ulxCMVcU6EU/s160-c/Valley%252520Sunset.jpg",
- "https://lh6.googleusercontent.com/-DOz5I2E2oMQ/URqvKMND1kI/AAAAAAAAAbs/Iqf0IsInleo/s160-c/Windmill%252520Sunrise.jpg",
- "https://lh5.googleusercontent.com/-biyiyWcJ9MU/URqvKculiAI/AAAAAAAAAbs/jyPsCplJOpE/s160-c/Windmill.jpg",
- "https://lh4.googleusercontent.com/-PDT167_xRdA/URqvK36mLcI/AAAAAAAAAbs/oi2ik9QseMI/s160-c/Windmills.jpg",
- "https://lh5.googleusercontent.com/-kI_QdYx7VlU/URqvLXCB6gI/AAAAAAAAAbs/N31vlZ6u89o/s160-c/Yet%252520Another%252520Rockaway%252520Sunset.jpg",
- "https://lh4.googleusercontent.com/-e9NHZ5k5MSs/URqvMIBZjtI/AAAAAAAAAbs/1fV810rDNfQ/s160-c/Yosemite%252520Tree.jpg", };
- }
ImageDownLoader類,異步下載的核心類,保存圖片到手機緩存,將圖片加入LruCache中等等
- package com.example.asyncimageloader;
- import java.io.IOException;
- import java.net.HttpURLConnection;
- import java.net.URL;
- import java.util.concurrent.ExecutorService;
- import java.util.concurrent.Executors;
- import android.content.Context;
- import android.graphics.Bitmap;
- import android.graphics.BitmapFactory;
- import android.os.Handler;
- import android.os.Message;
- import android.support.v4.util.LruCache;
- public class ImageDownLoader {
- /**
- * 緩存Image的類,當存儲Image的大小大於LruCache設定的值,系統自動釋放內存
- */
- private LruCache<String, Bitmap> mMemoryCache;
- /**
- * 操作文件相關類對象的引用
- */
- private FileUtils fileUtils;
- /**
- * 下載Image的線程池
- */
- private ExecutorService mImageThreadPool = null;
- public ImageDownLoader(Context context){
- //獲取系統分配給每個應用程序的最大內存,每個應用系統分配32M
- int maxMemory = (int) Runtime.getRuntime().maxMemory();
- int mCacheSize = maxMemory / 8;
- //給LruCache分配1/8 4M
- mMemoryCache = new LruCache<String, Bitmap>(mCacheSize){
- //必須重寫此方法,來測量Bitmap的大小
- @Override
- protected int sizeOf(String key, Bitmap value) {
- return value.getRowBytes() * value.getHeight();
- }
- };
- fileUtils = new FileUtils(context);
- }
- /**
- * 獲取線程池的方法,因為涉及到並發的問題,我們加上同步鎖
- * @return
- */
- public ExecutorService getThreadPool(){
- if(mImageThreadPool == null){
- synchronized(ExecutorService.class){
- if(mImageThreadPool == null){
- //為了下載圖片更加的流暢,我們用了2個線程來下載圖片
- mImageThreadPool = Executors.newFixedThreadPool(2);
- }
- }
- }
- return mImageThreadPool;
- }
- /**
- * 添加Bitmap到內存緩存
- * @param key
- * @param bitmap
- */
- public void addBitmapToMemoryCache(String key, Bitmap bitmap) {
- if (getBitmapFromMemCache(key) == null && bitmap != null) {
- mMemoryCache.put(key, bitmap);
- }
- }
- /**
- * 從內存緩存中獲取一個Bitmap
- * @param key
- * @return
- */
- public Bitmap getBitmapFromMemCache(String key) {
- return mMemoryCache.get(key);
- }
- /**
- * 先從內存緩存中獲取Bitmap,如果沒有就從SD卡或者手機緩存中獲取,SD卡或者手機緩存
- * 沒有就去下載
- * @param url
- * @param listener
- * @return
- */
- public Bitmap downloadImage(final String url, final onImageLoaderListener listener){
- //替換Url中非字母和非數字的字符,這裡比較重要,因為我們用Url作為文件名,比如我們的Url
- //是Http://xiaanming/abc.jpg;用這個作為圖片名稱,系統會認為xiaanming為一個目錄,
- //我們沒有創建此目錄保存文件就會報錯
- final String subUrl = url.replaceAll("[^\\w]", "");
- Bitmap bitmap = showCacheBitmap(subUrl);
- if(bitmap != null){
- return bitmap;
- }else{
- final Handler handler = new Handler(){
- @Override
- public void handleMessage(Message msg) {
- super.handleMessage(msg);
- listener.onImageLoader((Bitmap)msg.obj, url);
- }
- };
- getThreadPool().execute(new Runnable() {
- @Override
- public void run() {
- Bitmap bitmap = getBitmapFormUrl(url);
- Message msg = handler.obtainMessage();
- msg.obj = bitmap;
- handler.sendMessage(msg);
- try {
- //保存在SD卡或者手機目錄
- fileUtils.savaBitmap(subUrl, bitmap);
- } catch (IOException e) {
- e.printStackTrace();
- }
- //將Bitmap 加入內存緩存
- addBitmapToMemoryCache(subUrl, bitmap);
- }
- });
- }
- return null;
- }
- /**
- * 獲取Bitmap, 內存中沒有就去手機或者sd卡中獲取,這一步在getView中會調用,比較關鍵的一步
- * @param url
- * @return
- */
- public Bitmap showCacheBitmap(String url){
- if(getBitmapFromMemCache(url) != null){
- return getBitmapFromMemCache(url);
- }else if(fileUtils.isFileExists(url) && fileUtils.getFileSize(url) != 0){
- //從SD卡獲取手機裡面獲取Bitmap
- Bitmap bitmap = fileUtils.getBitmap(url);
- //將Bitmap 加入內存緩存
- addBitmapToMemoryCache(url, bitmap);
- return bitmap;
- }
- return null;
- }
- /**
- * 從Url中獲取Bitmap
- * @param url
- * @return
- */
- private Bitmap getBitmapFormUrl(String url) {
- Bitmap bitmap = null;
- HttpURLConnection con = null;
- try {
- URL mImageUrl = new URL(url);
- con = (HttpURLConnection) mImageUrl.openConnection();
- con.setConnectTimeout(10 * 1000);
- con.setReadTimeout(10 * 1000);
- con.setDoInput(true);
- con.setDoOutput(true);
- bitmap = BitmapFactory.decodeStream(con.getInputStream());
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- if (con != null) {
- con.disconnect();
- }
- }
- return bitmap;
- }
- /**
- * 取消正在下載的任務
- */
- public synchronized void cancelTask() {
- if(mImageThreadPool != null){
- mImageThreadPool.shutdownNow();
- mImageThreadPool = null;
- }
- }
- /**
- * 異步下載圖片的回調接口
- * @author len
- *
- */
- public interface onImageLoaderListener{
- void onImageLoader(Bitmap bitmap, String url);
- }
- }
ImageDownLoader中有幾個方法比較重要
首先我們需要重寫sizeOf(String key, Bitmap value)來計算圖片的大小,默認返回圖片的數量
downloadImage(final String url, final onImageLoaderListener listener)先去LruCache查看Image,沒有再去手機緩存中查看,在沒有則開啟線程下載,這裡我們提供了一個回調接口,回調方法中我們將Bitmap和圖片Url作為參數,String subUrl = url.replaceAll("[^\\w]", "") 我在代碼中注釋寫的比較清楚
showCacheBitmap(String url)方法,此方法在Adapter中的getView()當中調用,如果getView()中不調用此方法試試你就知道效果了
ImageAdapter GridView的適配器類,主要是GridView滑動的時候取消下載任務,靜止的時候去下載當前顯示的item的圖片,其他也沒什麼不同了
- package com.example.asyncimageloader;
- import android.content.Context;
- import android.graphics.Bitmap;
- import android.view.View;
- import android.view.ViewGroup;
- import android.widget.AbsListView;
- import android.widget.AbsListView.OnScrollListener;
- import android.widget.BaseAdapter;
- import android.widget.GridView;
- import android.widget.ImageView;
- import com.example.asyncimageloader.ImageDownLoader.onImageLoaderListener;
- public class ImageAdapter extends BaseAdapter implements OnScrollListener{
- /**
- * 上下文對象的引用
- */
- private Context context;
- /**
- * Image Url的數組
- */
- private String [] imageThumbUrls;
- /**
- * GridView對象的應用
- */
- private GridView mGridView;
- /**
- * Image 下載器
- */
- private ImageDownLoader mImageDownLoader;
- /**
- * 記錄是否剛打開程序,用於解決進入程序不滾動屏幕,不會下載圖片的問題。
- * 參考http://blog.csdn.net/guolin_blog/article/details/9526203#comments
- */
- private boolean isFirstEnter = true;
- /**
- * 一屏中第一個item的位置
- */
- private int mFirstVisibleItem;
- /**
- * 一屏中所有item的個數
- */
- private int mVisibleItemCount;
- public ImageAdapter(Context context, GridView mGridView, String [] imageThumbUrls){
- this.context = context;
- this.mGridView = mGridView;
- this.imageThumbUrls = imageThumbUrls;
- mImageDownLoader = new ImageDownLoader(context);
- mGridView.setOnScrollListener(this);
- }
- @Override
- public void onScrollStateChanged(AbsListView view, int scrollState) {
- //僅當GridView靜止時才去下載圖片,GridView滑動時取消所有正在下載的任務
- if(scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE){
- showImage(mFirstVisibleItem, mVisibleItemCount);
- }else{
- cancelTask();
- }
- }
- /**
- * GridView滾動的時候調用的方法,剛開始顯示GridView也會調用此方法
- */
- @Override
- public void onScroll(AbsListView view, int firstVisibleItem,
- int visibleItemCount, int totalItemCount) {
- mFirstVisibleItem = firstVisibleItem;
- mVisibleItemCount = visibleItemCount;
- // 因此在這裡為首次進入程序開啟下載任務。
- if(isFirstEnter && visibleItemCount > 0){
- showImage(mFirstVisibleItem, mVisibleItemCount);
- isFirstEnter = false;
- }
- }
- @Override
- public int getCount() {
- return imageThumbUrls.length;
- }
- @Override
- public Object getItem(int position) {
- return imageThumbUrls[position];
- }
- @Override
- public long getItemId(int position) {
- return position;
- }
- @Override
- public View getView(int position, View convertView, ViewGroup parent) {
- ImageView mImageView;
- final String mImageUrl = imageThumbUrls[position];
- if(convertView == null){
- mImageView = new ImageView(context);
- }else{
- mImageView = (ImageView) convertView;
- }
- mImageView.setLayoutParams(new GridView.LayoutParams(150, 150));
- mImageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
- //給ImageView設置Tag,這裡已經是司空見慣了
- mImageView.setTag(mImageUrl);
- /*******************************去掉下面這幾行試試是什麼效果****************************/
- Bitmap bitmap = mImageDownLoader.showCacheBitmap(mImageUrl.replaceAll("[^\\w]", ""));
- if(bitmap != null){
- mImageView.setImageBitmap(bitmap);
- }else{
- mImageView.setImageDrawable(context.getResources().getDrawable(R.drawable.ic_empty));
- }
- /**********************************************************************************/
- return mImageView;
- }
- /**
- * 顯示當前屏幕的圖片,先會去查找LruCache,LruCache沒有就去sd卡或者手機目錄查找,在沒有就開啟線程去下載
- * @param firstVisibleItem
- * @param visibleItemCount
- */
- private void showImage(int firstVisibleItem, int visibleItemCount){
- Bitmap bitmap = null;
- for(int i=firstVisibleItem; i<firstVisibleItem + visibleItemCount; i++){
- String mImageUrl = imageThumbUrls[i];
- final ImageView mImageView = (ImageView) mGridView.findViewWithTag(mImageUrl);
- bitmap = mImageDownLoader.downloadImage(mImageUrl, new onImageLoaderListener() {
- @Override
- public void onImageLoader(Bitmap bitmap, String url) {
- if(mImageView != null && bitmap != null){
- mImageView.setImageBitmap(bitmap);
- }
- }
- });
- //if(bitmap != null){
- // mImageView.setImageBitmap(bitmap);
- //}else{
- // mImageView.setImageDrawable(context.getResources().getDrawable(R.drawable.ic_empty));
- //}
- }
- }
- /**
- * 取消下載任務
- */
- public void cancelTask(){
- mImageDownLoader.cancelTask();
- }
- }
MainActivity 裡面一個GridView,然後提供一個系統菜單來刪除手機上的緩存圖片,直接上代碼,比較簡單所以裡面也沒有注釋
- package com.example.asyncimageloader;
- import android.app.Activity;
- import android.os.Bundle;
- import android.view.Menu;
- import android.view.MenuItem;
- import android.widget.GridView;
- import android.widget.Toast;
- public class MainActivity extends Activity {
- private GridView mGridView;
- private String [] imageThumbUrls = Images.imageThumbUrls;
- private ImageAdapter mImageAdapter;
- private FileUtils fileUtils;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- fileUtils = new FileUtils(this);
- mGridView = (GridView) findViewById(R.id.gridView);
- mImageAdapter = new ImageAdapter(this, mGridView, imageThumbUrls);
- mGridView.setAdapter(mImageAdapter);
- }
- @Override
- protected void onDestroy() {
- mImageAdapter.cancelTask();
- super.onDestroy();
- }
- @Override
- public boolean onCreateOptionsMenu(Menu menu) {
- super.onCreateOptionsMenu(menu);
- menu.add("刪除手機中圖片緩存");
- return super.onCreateOptionsMenu(menu);
- }
- @Override
- public boolean onOptionsItemSelected(MenuItem item) {
- switch (item.getItemId()) {
- case 0:
- fileUtils.deleteFile();
- Toast.makeText(getApplication(), "清空緩存成功", Toast.LENGTH_SHORT).show();
- break;
- }
- return super.onOptionsItemSelected(item);
- }
- }
MainActivity的布局文件
- <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- tools:context=".MainActivity" >
- <GridView
- android:id="@+id/gridView"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:stretchMode="columnWidth"
- android:columnWidth="90dip"
- android:verticalSpacing="10dip"
- android:horizontalSpacing="10dip"
- android:cacheColorHint="@android:color/transparent"
- android:numColumns="auto_fit" >
- </GridView>
- </RelativeLayout>
因為有網絡操作和對sd卡的操作,所以我們必須加上相對應的權限
- <uses-permission android:name="android.permission.INTERNET" />
- <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
好了,代碼就全部介紹完了,我們運行下程序看看效果,這裡的效果是用一個線程下載圖片的效果,可能有一些不完整,想看看效果自己動手試試
好了,今天的講解到此結束,有疑問的朋友請在下面留言,源碼裡面GridView的布局文件 columnWedth設置了120dip,有點丑,大家可以改成90dip
源碼下載
如上一節中所講的那樣創建了ApiDemo工程後,我們就可以進行每個示例代碼的分
登錄應用程序的屏幕,詢問憑據登錄到一些特定的應用。可能需要登錄到Facebook,微博等本章介紹了,如何創建一個登錄界面,以及如何管理安全問題和錯誤嘗試。首先,必須定義兩
登錄應用程序的屏幕,詢問憑據登錄到一些特定的應用。可能需要登錄到Facebook,微博等本章介紹了,如何創建一個登錄界面,以及如何管理安全問題和錯誤嘗試。首先,必須定義兩
工作中有做過手機App項目,前端和android或ios程序員配合完成整個項目的開發,開發過程中與ios程序配合基本沒什麼問題,而android各種機子和rom的