Android编程学习之异步加载图片的方法

2019-12-10 19:58:56于海丽
  • public void Clean(ImageView image) {   for (int j = 0; j < picturesToLoad.size();) {  
  • if (picturesToLoad.get(j).imageView == image)   picturesToLoad.remove(j);  
  • else  ++j;  
  • }   }  
  • }   // 图片加载线程  
  • class PicturesLoader extends Thread {   public void run() {  
  • try {   while (true) {  
  • // 线程等待直到有图片加载在队列中   if (picturesQueue.picturesToLoad.size() == 0)  
  • synchronized (picturesQueue.picturesToLoad) {   picturesQueue.picturesToLoad.wait();  
  • }   if (picturesQueue.picturesToLoad.size() != 0) {  
  • PictureToLoad photoToLoad;   synchronized (picturesQueue.picturesToLoad) {  
  • photoToLoad = picturesQueue.picturesToLoad.pop();   }  
  • Bitmap bmp = getBitmap(photoToLoad.url);   // 写到手机内存中  
  • memoryCache.put(photoToLoad.url, bmp);   String tag = imageViews.get(photoToLoad.imageView);  
  • if (tag != null && tag.equals(photoToLoad.url)) {   BitmapDisplayer bd = new BitmapDisplayer(bmp,  
  • photoToLoad.imageView);   Activity activity = (Activity) photoToLoad.imageView  
  • .getContext();   activity.runOnUiThread(bd);  
  • }   }  
  • if (Thread.interrupted())   break;  
  • }   } catch (InterruptedException e) {  
  • // 在这里允许线程退出   }  
  • }   }  
  • // 在UI线程中显示Bitmap图像   class BitmapDisplayer implements Runnable {  
  • Bitmap bitmap;   ImageView imageView;  
  • public BitmapDisplayer(Bitmap bitmap, ImageView imageView) {   this.bitmap = bitmap;  
  • this.imageView = imageView;   }