ImageView異步加載網絡圖片

 

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit; java

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.util.Log; android

//加載圖片的類 網絡

public class AsyncImageLoader {
 private static final String TAG="AsyncImageLoader"; async

 private HashMap<String, SoftReference<Drawable>> imageCache;
 private BlockingQueue queue ;  
 private ThreadPoolExecutor executor ;
  
      public AsyncImageLoader() {
       imageCache = new HashMap<String, SoftReference<Drawable>>();
      
       // 線程池:最大50條,每次執行:1條,空閒線程結束的超時時間:180秒
       queue = new LinkedBlockingQueue();
       executor = new ThreadPoolExecutor(1, 50, 180, TimeUnit.SECONDS, queue);
      }
  
//      public Drawable loadDrawable(final Context context, final String imageUrl, final ImageCallback imageCallback) {
//          if (imageCache.containsKey(imageUrl)) {//key 的名稱錯了,找了很久。。
      public Drawable loadDrawable(final Context context, final String imgUrl, final ImageCallback imageCallback) {
          if (imageCache.containsKey(imgUrl)) {//key 的名稱錯了,找了很久。。
              SoftReference<Drawable> softReference = imageCache.get(imgUrl);
              Drawable drawable = softReference.get();
              if (drawable != null) {
                  return drawable;
              }
          }
          final Handler handler = new Handler() {
              public void handleMessage(Message message) {
                  imageCallback.imageLoaded((Drawable) message.obj, imgUrl);
              }
          };
         
          // 用線程池來作下載圖片的任務
          executor.execute(new Runnable() {
              @Override
              public void run() {
                  Drawable drawable = loadImageFromUrl(context, imgUrl);
                  imageCache.put(imgUrl, new SoftReference<Drawable>(drawable));
                  Message message = handler.obtainMessage(0, drawable);
                  handler.sendMessage(message);
              }
          });
         
          return null;
      }
  
     // 網絡圖片先下載到本地cache目錄保存,以imagUrl的圖片文件名保存。若是有同名文件在cache目錄就從本地加載
  public static Drawable loadImageFromUrl(Context context, String imageUrl) {
   Drawable drawable = null; 
         if(imageUrl == null )
             return null; 
         String imagePath = ""; 
         String   fileName   = ""; 
              
         // 獲取url中圖片的文件名與後綴 
         if(imageUrl!=null&&imageUrl.length()!=0){  
             fileName  = imageUrl.substring(imageUrl.lastIndexOf("/")+1);
             Log.v("get the name form ImgUrl", fileName);
         } 
          
         // 圖片在手機本地的存放路徑,注意:fileName爲空的狀況 
//         String cache = android.os.Environment.getDownloadCacheDirectory().toString();
//         Log.v("getDownloadCacheDirectory()", cache);
         String cachepath = context.getCacheDir()+"/";                
         Log.v("get the CachePath the Img to be saved into", cachepath);
         imagePath = cachepath + fileName;
        
//         Log.i(TAG,"imagePath = " + imagePath); 
         File file = new File(context.getCacheDir(),fileName);// 保存文件 
//         Log.i(TAG,"file.toString()=" + file.toString()); 
         if(!file.exists()&&!file.isDirectory()) 
         { 
             try { 
                 // 能夠在這裏經過文件名來判斷,是否本地有此圖片 
                  
                 FileOutputStream   fos=new   FileOutputStream( file ); 
                 InputStream is = new URL(imageUrl).openStream(); 
                 int   data = is.read();  
                 while(data!=-1){  
                         fos.write(data);  
                         data=is.read(); 
                 }  
                 fos.close(); 
                 is.close(); 
//               drawable = Drawable.createFromStream( 
//                       new URL(imageUrl).openStream(), file.toString() ); // (InputStream) new URL(imageUrl).getContent(); 
                 drawable = Drawable.createFromPath(file.toString()); 
//                 Log.i(TAG, "file.exists()不文件存在,網上下載:" + drawable.toString()); 
             } catch (IOException e) { 
                 Log.e(TAG, e.toString() + "圖片下載及保存時出現異常!"); 
             } 
         }else 
         {
          
             drawable = Drawable.createFromPath(file.toString()); 
//             Log.i("test", "file.exists()文件存在,本地獲取"); 
         }
         return drawable ;
  }
  
      public interface ImageCallback {
          public void imageLoaded(Drawable imageDrawable, String imageUrl);
      } ide

} url

 

 

//引用處 .net

private AsyncImageLoader asyncImageLoader;asyncImageLoader = new AsyncImageLoader();
    String imageUrl=http://i1.itc.cn/20111107/70b_3bbc312b_a7d6_24bf_5e85_f8f181f25d0a_1.jpg; 線程

//圖片url orm

 act_head_img=(ImageView)findViewById(R.id.edit_act_head_img);
    act_head_img.setTag(imageUrl);
    Drawable cachedImage = asyncImageLoader.loadDrawable(getApplicationContext(),imageUrl,
      new ImageCallback() {
       public void imageLoaded(Drawable imageDrawable,
         String imageUrl) {
        ImageView imageViewByTag = (ImageView)act_head_img.findViewWithTag(imageUrl);
        if (imageViewByTag != null) {
         imageViewByTag.setImageDrawable(imageDrawable);
        }
       }
      });
    if (cachedImage == null) {
     act_head_img.setImageResource(R.drawable.ic_launcher);
    } else {
     act_head_img.setImageDrawable(cachedImage);
    } 圖片

相關文章
相關標籤/搜索