Android加載網絡圖片學習過程

轉自:http://blog.csdn.net/toyuexinshangwan/article/details/8194816

其他相關的文章:開源框架ImageLoader

http://blog.csdn.net/wwj_748/article/details/10079311

http://blog.csdn.net/yueqinglkong/article/details/27660107


好多應用都需要加載網絡圖片,那ToYueXinShangWan,這是比須熟練掌握的一個點,下面開始學習:

一、最簡單加載網絡圖片

從網絡上取圖片數據,顯示在應用中,簡單不贅述:

[java] view plaincopy
  1.       try {  
  2.     URL url = new URL(path); //path圖片的網絡地址  
  3.     HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();  
  4.     if(httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK){  
  5.         Bitmap bitmap  = BitmapFactory.decodeStream(httpURLConnection.getInputStream());  
  6.         imageview.setImageBitmap(bitmap);//加載到ImageView上  
  7.         System.out.println("加載網絡圖片完成");  
  8.     }else{  
  9.         System.out.println("加載網絡圖片失敗");  
  10.     }  
  11. catch (IOException e) {  
  12.     e.printStackTrace();  
  13. }  

二、輕量級異步加載圖片

不會有人用第一種方法加載,連接網絡和從網絡取數據,花費部分時間,阻礙主線程,影響UI效果!

解決方案是:異步加載。先給ImageView設置一張圖片,在異步任務中取數據,當從網絡中取數據中和取數據失敗時,就一直顯示原來圖片,當完成取數據時則再把新圖片加載到ImageView上。

根據上面思路,就可以直接動手寫了,爲了便於代碼複用,將加載圖片寫在一個工具類Utils中:

[java] view plaincopy
  1. package com.lizhen.loadimage;  
  2.   
  3. import java.io.IOException;  
  4. import java.io.InputStream;  
  5. import java.net.HttpURLConnection;  
  6. import java.net.URL;  
  7.   
  8. import android.graphics.Bitmap;  
  9. import android.graphics.BitmapFactory;  
  10. import android.os.Handler;  
  11. import android.os.Message;  
  12.   
  13. public class Utils {  
  14.     public static void onLoadImage(final URL bitmapUrl,final OnLoadImageListener onLoadImageListener){  
  15.         final Handler handler = new Handler(){  
  16.             public void handleMessage(Message msg){  
  17.                 onLoadImageListener.OnLoadImage((Bitmap) msg.obj, null);  
  18.             }  
  19.     };  
  20.         new Thread(new Runnable(){  
  21.   
  22.             @Override  
  23.             public void run() {  
  24.                 // TODO Auto-generated method stub  
  25.                 URL imageUrl = bitmapUrl;  
  26.                 try {  
  27.                     HttpURLConnection conn = (HttpURLConnection) imageUrl.openConnection();  
  28.                     InputStream inputStream = conn.getInputStream();  
  29.                     Bitmap bitmap = BitmapFactory.decodeStream(inputStream);  
  30.                     Message msg = new Message();  
  31.                     msg.obj = bitmap;  
  32.                     handler.sendMessage(msg);  
  33.                 } catch (IOException e) {  
  34.                     // TODO Auto-generated catch block  
  35.                     e.printStackTrace();  
  36.                 }  
  37.             }  
  38.               
  39.         }).start();  
  40.   
  41.     }  
  42.     public interface OnLoadImageListener{  
  43.         public void OnLoadImage(Bitmap bitmap,String bitmapPath);  
  44.     }  
  45. }  
然後在需要加載圖片的地方調用調用onLoadImage()方法即可,在接口OnLoadImageListener的回調方法OnLoadImage()中,如:

[java] view plaincopy
  1.   Utils.onLoadImage(url, new OnLoadImageListener() {  
  2.     @Override  
  3.     public void OnLoadImage(Bitmap bitmap, String bitmapPath) {  
  4.         // TODO Auto-generated method stub  
  5.         if(bitmap!=null){  
  6.             imageview.setImageBitmap(bitmap);  
  7.         }  
  8.     }  
  9. });  
wangluo jiazai zhong -->讀取完網絡數據後,加載圖片效果---->
三、第二種方法的弊端是,當有大量圖片需要加載時,會啓動很多線程,避免出現這種情況的方法是,定義線程個數,當線程數達到最多時,不再開啓,直到有一個線程結束,再開啓一個線程;這種做法相當於

引入ExecutorService接口,於是代碼可以優化如下:

       在主線程中加入:private ExecutorService executorService = Executors.newFixedThreadPool(5); 

在相應位置修改代碼如下:

[java] view plaincopy
  1. executorService.submit(new Runnable(){  
  2.   
  3.         @Override  
  4.         public void run() {  
  5.             // TODO Auto-generated method stub  
  6.             URL imageUrl = bitmapUrl;  
  7.             try {  
  8.                  System.out.println(Thread.currentThread().getName() + "線程被調用了。");   
  9.                 HttpURLConnection conn = (HttpURLConnection) imageUrl.openConnection();  
  10.                 InputStream inputStream = conn.getInputStream();  
  11.                 Bitmap bitmap = BitmapFactory.decodeStream(inputStream);  
  12.                 Message msg = new Message();  
  13.                 msg.obj = bitmap;  
  14.                 handler.sendMessage(msg);  
  15.             } catch (IOException e) {  
  16.                 // TODO Auto-generated catch block  
  17.                 e.printStackTrace();  
  18.             }  
  19.              System.out.println(Thread.currentThread().getName() + "線程結束。");   
  20.         }  
  21.     });  

線程池大小爲3,運行5個線程,我的輸出結果爲:


這裏有關線程池的概念用法寫在另一篇文章裏!


四、關於方法二的改進,考慮到效率問題,可以引入緩存機制,把圖片保留在本地,只需在線程run方法最後加上如下代碼:

[java] view plaincopy
  1. //緩存  
  2.                     if(Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)){  
  3.                         System.out.println("存在sd卡");  
  4.                         File cacheFile = new File(Environment.getExternalStorageDirectory()+"/cacheFile");  
  5.                         System.out.println(cacheFile.getPath());  
  6.                         if(!cacheFile.exists())  
  7.                             cacheFile.mkdir();  
  8.                         System.out.println(cacheFile.exists());  
  9.                         File imageCache = new File(cacheFile.getPath()+"/netwrok.png");  
  10.                         FileOutputStream fos = new FileOutputStream(imageCache);  
  11.                         BufferedOutputStream bos = new BufferedOutputStream(fos);    
  12.                         bitmap.compress(Bitmap.CompressFormat.PNG, 80, bos);     
  13.                         bos.flush();     
  14.                         bos.close();     
  15.                     }  

另一種把圖片緩存在內存中使用如下步驟:

1、主線程 public Map<String, SoftReference<Drawable>> imageCache = new HashMap<String, SoftReference<Drawable>>();

2、如果有緩存則讀取緩存中數據,如果沒有,則從網絡獲取數據;

 //如果緩存過就從緩存中取出數據
        if (imageCache.containsKey(imageUrl)) {
            SoftReference<Drawable> softReference = imageCache.get(imageUrl);
            if (softReference.get() != null) {
                return softReference.get();//得到緩存中的Drawable
            }
        }

3、在網絡獲取數據時,不要忘記添加imageCache信息

 imageCache.put(imageUrl, new SoftReference<Drawable>(drawable));

注意:SoftReference<Drawable>就是用來處理解決大量圖片下載內存溢出的問題的,還有Bitmap與Drawable之間的轉換,在其他文章中將做總結!

2012 /11/18 1:26 太晚了,沒想這問題會花費這麼長時間;

發佈了28 篇原創文章 · 獲贊 7 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章