2013-01-09 51 views
0

裝載大位圖我試圖在應用程序中顯示大位圖,我continuesly越來越OOM異常,OOM異常,而在Android的

下面是ImageLoader的類我用

public class ImageLoader { 

    MemoryCache memoryCache=new MemoryCache(); 
    FileCache fileCache; 
    private Map<ImageView, String> imageViews=Collections.synchronizedMap(new WeakHashMap<ImageView, String>()); 

    public ImageLoader(Context context){ 
     //Make the background thead low priority. This way it will not affect the UI performance 
     photoLoaderThread.setPriority(Thread.NORM_PRIORITY-1); 

     fileCache=new FileCache(context); 
    } 

// final int stub_id=R.drawable.stub; 
    public void DisplayImage(String url,ImageView imageView) 
    { 
     imageViews.put(imageView, url); 

//  Bitmap bitmap=createScaledBitmap(memoryCache.get(url), 100,100,0); 
     Bitmap bitmap=memoryCache.get(url); 
     // Bitmap bitmaps=bitmap.createScaledBitmap(bitmap, 0, 100, 100); 

     if(bitmap!=null) 
     { 
      imageView.setBackgroundDrawable(new BitmapDrawable(bitmap)); 

      System.gc(); 
//   bitmap.recycle(); 
//   bitmap=null; 
//   imageView.setImageBitmap(getRoundedCornerBitmap(bitmap, 10,70,70)); 
//   imageView.setImageBitmap(bitmap); 
//   Log.v("first", "first"); 
     } 
     else 
     { 
      queuePhoto(url, imageView); 
//   Log.v("second", "second"); 

     }  
    } 

    private Bitmap createScaledBitmap(Bitmap bitmap, int i, int j, int k) { 
     // TODO Auto-generated method stub 
     return null; 
    } 

    private void queuePhoto(String url, ImageView imageView) 
    { 
     //This ImageView may be used for other images before. So there may be some old tasks in the queue. We need to discard them. 
     photosQueue.Clean(imageView); 
     PhotoToLoad p=new PhotoToLoad(url, imageView); 
     synchronized(photosQueue.photosToLoad){ 
      photosQueue.photosToLoad.push(p); 
      photosQueue.photosToLoad.notifyAll(); 
     } 

     //start thread if it's not started yet 
     if(photoLoaderThread.getState()==Thread.State.NEW) 
      photoLoaderThread.start(); 
    } 

    public Bitmap getBitmap(String url) 
    { 
     File f=fileCache.getFile(url); 

     //from SD cache 
     Bitmap b = decodeFile(f); 
     if(b!=null) 
      return b; 

     //from web 
     try { 
      Bitmap bitmap=null; 
      URL imageUrl = new URL(url); 
      HttpURLConnection conn = (HttpURLConnection)imageUrl.openConnection(); 
      conn.setConnectTimeout(30000); 
      conn.setReadTimeout(30000); 
      InputStream is=conn.getInputStream(); 
      OutputStream os = new FileOutputStream(f); 
      Utils.CopyStream(is, os); 
      os.close(); 
      bitmap = decodeFile(f); 
      return bitmap; 
     } catch (Exception ex){ 
      ex.printStackTrace(); 
      return null; 
     } 
    }//Lalit 



    private Bitmap decodeFile(File f){ 
     try { 
      //decode image size 
      BitmapFactory.Options o = new BitmapFactory.Options(); 
      o.inJustDecodeBounds = true; 
      FileInputStream stream1=new FileInputStream(f); 
      BitmapFactory.decodeStream(stream1,null,o); 
      stream1.close(); 

      //Find the correct scale value. It should be the power of 2. 
      final int REQUIRED_SIZE=Wall.width; 
      final int REQUIRED_SIZE1=Wall.height; 
      int width_tmp=o.outWidth, height_tmp=o.outHeight; 
      int scale=1; 
      while(true){ 
       if(width_tmp/2<REQUIRED_SIZE || height_tmp/2<REQUIRED_SIZE) 
        break; 
       width_tmp/=2; 
       height_tmp/=2; 
       scale*=2; 
      } 

      //decode with inSampleSize 
      BitmapFactory.Options o2 = new BitmapFactory.Options(); 
      o2.inSampleSize=scale; 
      FileInputStream stream2=new FileInputStream(f); 
      Bitmap bitmap=BitmapFactory.decodeStream(stream2, null, o2); 
      stream2.close(); 
      return bitmap; 
     } catch (FileNotFoundException e) { 
     } 
     catch (IOException e) { 
      e.printStackTrace(); 
     } 
     return null; 
    } 






    //Task for the queue 
    private class PhotoToLoad 
    { 
     public String url; 
     public ImageView imageView; 
     public PhotoToLoad(String u, ImageView i){ 
      url=u; 
      imageView=i; 
     } 
    } 

    PhotosQueue photosQueue=new PhotosQueue(); 

    public void stopThread() 
    { 
     photoLoaderThread.interrupt(); 
    } 

    //stores list of photos to download 
    class PhotosQueue 
    { 
     private Stack<PhotoToLoad> photosToLoad=new Stack<PhotoToLoad>(); 

     //removes all instances of this ImageView 
     public void Clean(ImageView image) 
     { 
      for(int j=0 ;j<photosToLoad.size();){ 
       if(photosToLoad.get(j).imageView==image) 
        photosToLoad.remove(j); 
       else 
        ++j; 
      } 
     } 
    } 

    class PhotosLoader extends Thread { 
     public void run() { 
      try { 
       while(true) 
       { 
        //thread waits until there are any images to load in the queue 
        if(photosQueue.photosToLoad.size()==0) 
         synchronized(photosQueue.photosToLoad){ 
          photosQueue.photosToLoad.wait(); 
         } 
        if(photosQueue.photosToLoad.size()!=0) 
        { 
         PhotoToLoad photoToLoad; 
         synchronized(photosQueue.photosToLoad){ 
          photoToLoad=photosQueue.photosToLoad.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 a=(Activity)photoToLoad.imageView.getContext(); 
          a.runOnUiThread(bd); 
         } 
        } 
        if(Thread.interrupted()) 
         break; 
       } 
      } catch (InterruptedException e) { 
       //allow thread to exit 
      } 
     } 
    } 

    PhotosLoader photoLoaderThread=new PhotosLoader(); 

    //Used to display bitmap in the UI thread 
    class BitmapDisplayer implements Runnable 
    { 
     Bitmap bitmap; 
     ImageView imageView; 
     public BitmapDisplayer(Bitmap b, ImageView i){bitmap=b;imageView=i;} 
     public void run() 
     { 
      if(bitmap!=null) 
       imageView.setBackgroundDrawable(new BitmapDrawable(bitmap)); 

     } 
    } 

    public void clearCache() { 
     memoryCache.clear(); 
     fileCache.clear(); 
    } 
    public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, int pixels,int width,int height) { 

     Bitmap output = Bitmap.createBitmap(width,height, Config.ARGB_8888); 
     Canvas canvas = new Canvas(output); 

     final int color = 0xff424242; 
     final Paint paint = new Paint(); 
     final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight()); 
     final RectF rectF = new RectF(rect); 
     final float roundPx = pixels; 

     paint.setAntiAlias(true); 
     canvas.drawARGB(0, 0, 0, 0); 
     paint.setColor(color); 
     canvas.drawRoundRect(rectF, roundPx, roundPx, paint); 

     paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN)); 
     canvas.drawBitmap(bitmap, rect, rect, paint); 

     return output; 
    } 
} 

我的MemoryCache類

public class MemoryCache { 

    private static final String TAG = "MemoryCache"; 
    private Map<String, Bitmap> cache=Collections.synchronizedMap(
      new LinkedHashMap<String, Bitmap>(10,1.5f,true));//Last argument true for LRU ordering 
    private long size=0;//current allocated size 
    private long limit=1000000;//max memory in bytes 

    public MemoryCache(){ 
     //use 25% of available heap size 
     setLimit(Runtime.getRuntime().maxMemory()/4); 
    } 

    public void setLimit(long new_limit){ 
     limit=new_limit; 
     Log.i(TAG, "MemoryCache will use up to "+limit/1024./1024.+"MB"); 
    } 

    public Bitmap get(String id){ 
     try{ 
      if(!cache.containsKey(id)) 
       return null; 
      //NullPointerException sometimes happen here http://code.google.com/p/osmdroid/issues/detail?id=78 
      return cache.get(id); 
     }catch(NullPointerException ex){ 
      ex.printStackTrace(); 
      return null; 
     } 
    } 

    public void put(String id, Bitmap bitmap){ 
     try{ 
      if(cache.containsKey(id)) 
       size-=getSizeInBytes(cache.get(id)); 
      cache.put(id, bitmap); 
      size+=getSizeInBytes(bitmap); 
      checkSize(); 
     }catch(Throwable th){ 
      th.printStackTrace(); 
     } 
    } 

    private void checkSize() { 
     Log.i(TAG, "cache size="+size+" length="+cache.size()); 
     if(size>limit){ 
      Iterator<Entry<String, Bitmap>> iter=cache.entrySet().iterator();//least recently accessed item will be the first one iterated 
      while(iter.hasNext()){ 
       Entry<String, Bitmap> entry=iter.next(); 
       size-=getSizeInBytes(entry.getValue()); 
       iter.remove(); 
       if(size<=limit) 
        break; 
      } 
      Log.i(TAG, "Clean cache. New size "+cache.size()); 
     } 
    } 

    public void clear() { 
     try{ 
      //NullPointerException sometimes happen here http://code.google.com/p/osmdroid/issues/detail?id=78 
      cache.clear(); 
      size=0; 
     }catch(NullPointerException ex){ 
      ex.printStackTrace(); 
     } 
    } 

    long getSizeInBytes(Bitmap bitmap) { 
     if(bitmap==null) 
      return 0; 
     return bitmap.getRowBytes() * bitmap.getHeight(); 
    } 
} 

這裏是logcat的輸出------------>

01-09 12:40:38.940: E/dalvikvm-heap(18736): 1123536-byte external allocation too large for this process. 
    01-09 12:40:38.979: D/GraphicsJNI(18736): Waiting for heap walker to free more memory 
    01-09 12:40:38.979: D/dalvikvm(18736): GC_FOR_MALLOC freed <1K, 53% free 4297K/8967K, external 22504K/23758K, paused 29ms 
    01-09 12:40:38.979: D/GraphicsJNI(18736): Heap walker done, retry to allocate 
    01-09 12:40:39.002: I/MemoryCache(18736): cache size=5691144 length=7 
    01-09 12:40:39.112: D/dalvikvm(18736): GC_EXTERNAL_ALLOC freed 89K, 53% free 4272K/8967K, external 21905K/22856K, paused 42ms 
    01-09 12:40:39.127: E/dalvikvm-heap(18736): 2457600-byte external allocation too large for this process. 
    01-09 12:40:39.167: D/GraphicsJNI(18736): Waiting for heap walker to free more memory 
    01-09 12:40:39.167: D/dalvikvm(18736): GC_FOR_MALLOC freed <1K, 53% free 4272K/8967K, external 21905K/22856K, paused 28ms 
    01-09 12:40:39.167: D/GraphicsJNI(18736): Heap walker done, retry to allocate 
    01-09 12:40:39.206: D/dalvikvm(18736): GC_EXTERNAL_ALLOC freed 2K, 53% free 4270K/8967K, external 20808K/22856K, paused 38ms 
    01-09 12:40:39.252: I/MemoryCache(18736): cache size=8148744 length=8 
    01-09 12:40:39.323: D/dalvikvm(18736): GC_EXTERNAL_ALLOC freed 148K, 53% free 4253K/8967K, external 23218K/25256K, paused 42ms 
    01-09 12:40:39.331: E/dalvikvm-heap(18736): 960000-byte external allocation too large for this process. 
    01-09 12:40:39.370: D/GraphicsJNI(18736): Waiting for heap walker to free more memory 
    01-09 12:40:39.370: D/dalvikvm(18736): GC_FOR_MALLOC freed <1K, 53% free 4253K/8967K, external 23218K/25256K, paused 28ms 
    01-09 12:40:39.377: D/GraphicsJNI(18736): Heap walker done, retry to allocate 
    01-09 12:40:39.409: D/dalvikvm(18736): GC_EXTERNAL_ALLOC freed 1K, 53% free 4251K/8967K, external 23208K/25256K, paused 38ms 
    01-09 12:40:39.424: E/dalvikvm-heap(18736): 960000-byte external allocation too large for this process. 
    01-09 12:40:39.463: E/GraphicsJNI(18736): VM won't let us allocate 960000 bytes 
    01-09 12:40:39.463: D/dalvikvm(18736): GC_FOR_MALLOC freed 0K, 53% free 4251K/8967K, external 23208K/25256K, paused 28ms 
    01-09 12:40:39.463: D/skia(18736): --- decoder->decode returned false 
    01-09 12:40:39.463: W/dalvikvm(18736): threadid=16: thread exiting with uncaught exception (group=0x40018560) 
    01-09 12:40:39.471: E/AndroidRuntime(18736): FATAL EXCEPTION: Thread-26 
    01-09 12:40:39.471: E/AndroidRuntime(18736): java.lang.OutOfMemoryError: bitmap size exceeds VM budget 
    01-09 12:40:39.471: E/AndroidRuntime(18736): at android.graphics.BitmapFactory.nativeDecodeStream(Native Method) 
    01-09 12:40:39.471: E/AndroidRuntime(18736): at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:470) 
    01-09 12:40:39.471: E/AndroidRuntime(18736): at com.beerbro.utils.ImageLoader.decodeFile(ImageLoader.java:190) 
    01-09 12:40:39.471: E/AndroidRuntime(18736): at com.beerbro.utils.ImageLoader.getBitmap(ImageLoader.java:100) 
    01-09 12:40:39.471: E/AndroidRuntime(18736): at com.beerbro.utils.ImageLoader$PhotosLoader.run(ImageLoader.java:257) 
    01-09 12:40:39.471: W/ActivityManager(1320): Force finishing activity com.stellent.beerbro/.Wall 

我正在加載來自Facebook圖表api的數據,我正在獲取Firstpage數據,並且一次顯示整個數據。我認爲這會使內存增加很多。 那麼,如何處理大量的數據。 請幫忙

回答

0

您應該使用inJustDecodeBounds來解碼位圖大小而不將其加載到內存中。 ATM,如果你嘗試加載一個大的位圖,你可以在檢查它是否在緩存的大小範圍內之前創建它。

你不應該強制GC,特別是因爲它是異步運行的,並且system.gc強制它是同步的。 Bitmaps不會直接加載到Java堆上,所以任何從緩存中出來的東西都應該被回收。最後不要保留對位圖的引用。

總的來說,我會用LRUCache而不是你自己的緩存。

最後,由於偏見,我建議像enter link description here這樣的緩存圖像到磁盤,並使用LRUCache進行演出。

+0

你可以請教我如何使用LruCache,我認爲會有像Memorycache,ImageLoader這樣的Helper類,我可以在哪裏找到這些類。 – user1891910