程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> 關於JAVA >> 在Android的運用中完成收集圖片異步加載的辦法

在Android的運用中完成收集圖片異步加載的辦法

編輯:關於JAVA

在Android的運用中完成收集圖片異步加載的辦法。本站提示廣大學習愛好者:(在Android的運用中完成收集圖片異步加載的辦法)文章只能為提供參考,不一定能成為您想要的結果。以下是在Android的運用中完成收集圖片異步加載的辦法正文


媒介
其實很榮幸,入職一周以後就可以隨著兩個師兄做android開辟,師兄都是年夜神,身為小白的我只能多多進修,多多盡力。比來一段時光都忙的沒機遇總結,明天剛完成了android客戶端圖片異步加載的類,這裡記載一下(ps:其實我這裡都是參考網上開源完成)


道理
在ListView或許GridView中加載圖片的道理根本都是一樣的:

    先從內存緩存中獲得,取到則前往,取不到停止下一步
    從文件緩存中獲得,取到則前往並更新到內存緩存,取不到則停止停止下一步
    從收集高低載圖片,並更新內存緩存和文件緩存


流程圖以下:

同時,要留意線程的數目。普通在listview中加載圖片,年夜家都是開啟新的線程去加載,然則當疾速滑動時,很輕易形成OOM,是以須要掌握線程數目。我們可以經由過程線程池掌握線程的數目,詳細線程池的年夜小還須要依據處置器的情形和營業情形自行斷定

樹立線程池的辦法以下:

   

ExecutorService executorService = Executors.newFixedThreadPool(5); // 5是可變的 

文件緩存類

   

 import java.io.File; 
   
  import android.content.Context; 
   
  public class FileCache { 
    private static final String DIR_NAME = "your_dir"; 
    private File cacheDir; 
   
    public FileCache(Context context) { 
      // Find the directory to save cached images 
      if (android.os.Environment.getExternalStorageState().equals( 
          android.os.Environment.MEDIA_MOUNTED)) { 
        cacheDir = new File( 
            android.os.Environment.getExternalStorageDirectory(), 
            DIR_NAME); 
      } else { 
        cacheDir = context.getCacheDir(); 
      } 
   
      if (!cacheDir.exists()) { 
        cacheDir.mkdirs(); 
      } 
    } 
   
    public File getFile(String url) { 
      // Identify images by url's hash code 
      String filename = String.valueOf(url.hashCode()); 
   
      File f = new File(cacheDir, filename); 
   
      return f; 
    } 
   
    public void clear() { 
      File[] files = cacheDir.listFiles(); 
      if (files == null) { 
        return; 
      } else { 
        for (File f : files) { 
          f.delete(); 
        } 
      } 
    } 
  } 

內存緩存類
這裡應用了軟援用,Map<String, SoftReference<Bitmap>> cache,可以谷歌一下軟援用的機制,簡略的說:完成了map,同時當內存重要時可以被收受接管,不會形成內存洩漏

   

 import java.lang.ref.SoftReference; 
  import java.util.Collections; 
  import java.util.LinkedHashMap; 
  import java.util.Map; 
   
  import android.graphics.Bitmap; 
   
  public class MemoryCache { 
    private Map<String, SoftReference<Bitmap>> cache = Collections 
        .synchronizedMap(new LinkedHashMap<String, SoftReference<Bitmap>>( 
            10, 1.5f, true)); 
   
    public Bitmap get(String id) { 
      if (!cache.containsKey(id)) { 
        return null; 
      } 
   
      SoftReference<Bitmap> ref = cache.get(id); 
   
      return ref.get(); 
    } 
   
    public void put(String id, Bitmap bitmap) { 
      cache.put(id, new SoftReference<Bitmap>(bitmap)); 
    } 
   
    public void clear() { 
      cache.clear(); 
    } 
  } 

圖片加載類

  import java.io.File; 
  import java.io.FileInputStream; 
  import java.io.FileNotFoundException; 
  import java.io.FileOutputStream; 
  import java.io.InputStream; 
  import java.io.OutputStream; 
  import java.net.HttpURLConnection; 
  import java.net.URL; 
  import java.util.Collections; 
  import java.util.Map; 
  import java.util.WeakHashMap; 
  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.widget.ImageView; 
   
  public class ImageLoader { 
    /** 
     * Network time out 
     */ 
    private static final int TIME_OUT = 30000; 
    /** 
     * Default picture resource 
     */ 
    private static final int DEFAULT_BG = R.drawable.plate_list_head_bg; 
   
    /** 
     * Thread pool number 
     */ 
    private static final int THREAD_NUM = 5; 
   
    /** 
     * Memory image cache 
     */ 
    MemoryCache memoryCache = new MemoryCache(); 
   
    /** 
     * File image cache 
     */ 
    FileCache fileCache; 
   
    /** 
     * Judge image view if it is reuse 
     */ 
    private Map<ImageView, String> imageViews = Collections 
        .synchronizedMap(new WeakHashMap<ImageView, String>()); 
   
    /** 
     * Thread pool 
     */ 
    ExecutorService executorService; 
   
    /** 
     * Handler to display images in UI thread 
     */ 
    Handler handler = new Handler(); 
   
    public ImageLoader(Context context) { 
      fileCache = new FileCache(context); 
      executorService = Executors.newFixedThreadPool(THREAD_NUM); 
    } 
   
    public void disPlayImage(String url, ImageView imageView) { 
      imageViews.put(imageView, url); 
      Bitmap bitmap = memoryCache.get(url); 
      if (bitmap != null) { 
        // Display image from Memory cache 
        imageView.setImageBitmap(bitmap); 
      } else { 
        // Display image from File cache or Network 
        queuePhoto(url, imageView); 
      } 
    } 
   
    private void queuePhoto(String url, ImageView imageView) { 
      PhotoToLoad photoToLoad = new PhotoToLoad(url, imageView); 
      executorService.submit(new PhotosLoader(photoToLoad)); 
    } 
   
    private Bitmap getBitmap(String url) { 
      File f = fileCache.getFile(url); 
   
      // From File cache 
      Bitmap bmp = decodeFile(f); 
      if (bmp != null) { 
        return bmp; 
      } 
   
      // From Network 
      try { 
        Bitmap bitmap = null; 
        URL imageUrl = new URL(url); 
        HttpURLConnection conn = (HttpURLConnection) imageUrl 
            .openConnection(); 
        conn.setConnectTimeout(TIME_OUT); 
        conn.setReadTimeout(TIME_OUT); 
        conn.setInstanceFollowRedirects(true); 
        InputStream is = conn.getInputStream(); 
        OutputStream os = new FileOutputStream(f); 
        copyStream(is, os); 
        os.close(); 
        conn.disconnect(); 
        bitmap = decodeFile(f); 
        return bitmap; 
      } catch (Throwable ex) { 
        if (ex instanceof OutOfMemoryError) { 
          clearCache(); 
        } 
        return null; 
      } 
   
    } 
   
    private void copyStream(InputStream is, OutputStream os) { 
      int buffer_size = 1024; 
   
      try { 
        byte[] bytes = new byte[buffer_size]; 
        while (true) { 
          int count = is.read(bytes, 0, buffer_size); 
          if (count == -1) { 
            break; 
          } 
          os.write(bytes, 0, count); 
        } 
   
      } catch (Exception e) { 
   
      } 
    } 
   
    private Bitmap decodeFile(File f) { 
      try { 
        // TODO:Compress image size 
        FileInputStream fileInputStream = new FileInputStream(f); 
        Bitmap bitmap = BitmapFactory.decodeStream(fileInputStream); 
        return bitmap; 
   
      } catch (FileNotFoundException e) { 
        return null; 
      } 
    } 
   
    private void clearCache() { 
      memoryCache.clear(); 
      fileCache.clear(); 
    } 
   
    /** 
     * Task for the queue 
     * 
     * @author zhengyi.wzy 
     * 
     */ 
    private class PhotoToLoad { 
      public String url; 
      public ImageView imageView; 
   
      public PhotoToLoad(String url, ImageView imageView) { 
        this.url = url; 
        this.imageView = imageView; 
      } 
    } 
   
    /** 
     * Asynchronous to load picture 
     * 
     * @author zhengyi.wzy 
     * 
     */ 
    class PhotosLoader implements Runnable { 
      PhotoToLoad photoToLoad; 
   
      public PhotosLoader(PhotoToLoad photoToLoad) { 
        this.photoToLoad = photoToLoad; 
      } 
   
      private boolean imageViewReused(PhotoToLoad photoToLoad) { 
        String tag = imageViews.get(photoToLoad.imageView); 
        if (tag == null || !tag.equals(photoToLoad.url)) { 
          return true; 
        } 
   
        return false; 
      } 
   
      @Override 
      public void run() { 
        // Abort current thread if Image View reused 
        if (imageViewReused(photoToLoad)) { 
          return; 
        } 
   
        Bitmap bitmap = getBitmap(photoToLoad.url); 
   
        // Update Memory 
        memoryCache.put(photoToLoad.url, bitmap); 
   
        if (imageViewReused(photoToLoad)) { 
          return; 
        } 
   
        // Don't change UI in children thread 
        BitmapDisplayer bd = new BitmapDisplayer(bitmap, photoToLoad); 
        handler.post(bd); 
      } 
   
      class BitmapDisplayer implements Runnable { 
        Bitmap bitmap; 
        PhotoToLoad photoToLoad; 
   
        public BitmapDisplayer(Bitmap bitmap, PhotoToLoad photoToLoad) { 
          this.bitmap = bitmap; 
          this.photoToLoad = photoToLoad; 
        } 
   
        @Override 
        public void run() { 
          if (imageViewReused(photoToLoad)) { 
            return; 
          } 
   
          if (bitmap != null) { 
            photoToLoad.imageView.setImageBitmap(bitmap); 
          } else { 
            photoToLoad.imageView.setImageResource(DEFAULT_BG); 
          } 
        } 
   
      } 
    } 
  } 

挪用辦法

  ImageLoader imageLoader = new ImageLoader(context); 
  imageLoader.disPlayImage(imageUrl, imageView); 


  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved