现在的位置: 首页 > 综合 > 正文

处理内存泄漏

2013年09月01日 ⁄ 综合 ⁄ 共 10631字 ⁄ 字号 评论关闭
  1. 本人转载使用
  2. 方法二尝试后还是有些,方法一没有尝试过。

方法一:

  1.    protected Bitmap safeDecodeStream(Uri uri, int width, int height)  
  2.     throws FileNotFoundException{  
  3.         int scale = 1;  
  4.         BitmapFactory.Options options = new BitmapFactory.Options();  
  5.         android.content.ContentResolver resolver = this.ctx.getContentResolver();  
  6.           
  7.         if(width>0 || height>0){  
  8.             // Decode image size without loading all data into memory  
  9.             options.inJustDecodeBounds = true;  
  10.             BitmapFactory.decodeStream(  
  11.                     new BufferedInputStream(resolver.openInputStream(uri), 16*1024),  
  12.                     null,  
  13.                     options);  
  14.               
  15.             int w = options.outWidth;  
  16.             int h = options.outHeight;  
  17.             while (true) {  
  18.                 if ((width>0 && w/2 < width)  
  19.                         || (height>0 && h/2 < height)){  
  20.                     break;  
  21.                 }  
  22.                 w /= 2;  
  23.                 h /= 2;  
  24.                 scale *= 2;  
  25.             }  
  26.         }  
  27.   
  28.         // Decode with inSampleSize option  
  29.         options.inJustDecodeBounds = false;  
  30.         options.inSampleSize = scale;  
  31.         return BitmapFactory.decodeStream(  
  32.                 new BufferedInputStream(resolver.openInputStream(uri), 16*1024),   
  33.                 null,   
  34.                 options);  
  35.     }    

方法二:

  1. /** 
  2.  * 加载大图片工具类:解决android加载大图片时报OOM异常 
  3.  * 解决原理:先设置缩放选项,再读取缩放的图片数据到内存,规避了内存引起的OOM 
  4.  * @author: 张进  
  5.  
  6.  * @time:2011/7/28 
  7.  */  
  8. public class BitmapUtil {  
  9.   
  10.     public static final int UNCONSTRAINED = -1;  
  11.       
  12.     /* 
  13.   * 获得设置信息 
  14.   */  
  15.  public static Options getOptions(String path){  
  16.   Options options = new Options();  
  17.   options.inJustDecodeBounds = true;//只描边,不读取数据  
  18.   BitmapFactory.decodeFile(path, options);  
  19.   return options;  
  20.  }  
  21.    
  22.    
  23.  /** 
  24.   * 获得图像 
  25.   * @param path 
  26.   * @param options 
  27.   * @return 
  28.   * @throws FileNotFoundException 
  29.   */  
  30.  public static Bitmap getBitmapByPath(String path, Options options , int screenWidth , int screenHeight)throws FileNotFoundException{  
  31.   File file = new File(path);  
  32.   if(!file.exists()){  
  33.    throw new FileNotFoundException();  
  34.   }  
  35.   FileInputStream in = null;  
  36.   in = new FileInputStream(file);  
  37.   if(options != null){  
  38.    Rect r = getScreenRegion(screenWidth,screenHeight);  
  39.    int w = r.width();  
  40.    int h = r.height();  
  41.    int maxSize = w > h ? w : h;  
  42.    int inSimpleSize = computeSampleSize(options, maxSize, w * h);  
  43.    options.inSampleSize = inSimpleSize; //设置缩放比例  
  44.    options.inJustDecodeBounds = false;  
  45.   }  
  46.   Bitmap b = BitmapFactory.decodeStream(in, null, options);  
  47.   try {  
  48.    in.close();  
  49.   } catch (IOException e) {  
  50.    e.printStackTrace();  
  51.   }  
  52.   return b;  
  53.  }  
  54.    
  55.    
  56.       
  57.  private static Rect getScreenRegion(int width , int height) {  
  58.   return new Rect(0,0,width,height);  
  59.  }  
  60.   
  61.   
  62.  /** 
  63.   * 获取需要进行缩放的比例,即options.inSampleSize 
  64.   * @param options 
  65.   * @param minSideLength 
  66.   * @param maxNumOfPixels 
  67.   * @return 
  68.   */  
  69.  public static int computeSampleSize(BitmapFactory.Options options,  
  70.             int minSideLength, int maxNumOfPixels) {  
  71.         int initialSize = computeInitialSampleSize(options, minSideLength,  
  72.                 maxNumOfPixels);  
  73.   
  74.         int roundedSize;  
  75.         if (initialSize <= 8) {  
  76.             roundedSize = 1;  
  77.             while (roundedSize < initialSize) {  
  78.                 roundedSize <<= 1;  
  79.             }  
  80.         } else {  
  81.             roundedSize = (initialSize + 7) / 8 * 8;  
  82.         }  
  83.   
  84.         return roundedSize;  
  85.     }  
  86.   
  87.     private static int computeInitialSampleSize(BitmapFactory.Options options,  
  88.             int minSideLength, int maxNumOfPixels) {  
  89.         double w = options.outWidth;  
  90.         double h = options.outHeight;  
  91.   
  92.         int lowerBound = (maxNumOfPixels == UNCONSTRAINED) ? 1 :  
  93.                 (int) Math.ceil(Math.sqrt(w * h / maxNumOfPixels));  
  94.         int upperBound = (minSideLength == UNCONSTRAINED) ? 128 :  
  95.                 (int) Math.min(Math.floor(w / minSideLength),  
  96.                 Math.floor(h / minSideLength));  
  97.   
  98.         if (upperBound < lowerBound) {  
  99.             // return the larger one when there is no overlapping zone.  
  100.             return lowerBound;  
  101.         }  
  102.   
  103.         if ((maxNumOfPixels == UNCONSTRAINED) &&  
  104.                 (minSideLength == UNCONSTRAINED)) {  
  105.             return 1;  
  106.         } else if (minSideLength == UNCONSTRAINED) {  
  107.             return lowerBound;  
  108.         } else {  
  109.             return upperBound;  
  110.         }  
  111.     }  
  112.       
  113.    
  114. }

但是上面的方法也不是万能的,同样在很多的大图片的情况下照样存在,经查看Gallery中的图片加载时候发现同样会有问题,但是这个内存泄漏是在某张图片触发时产生,经过一段时间就没有了,所以GALLERY采用了延迟重新加载的方式再次读取这张图片。所以我们可以借鉴他的这个特点加上我们自己的对图片大小采样率的判断即可以避免这个问题。

 protected Bitmap load(RenderView view) {
        final Config config = mConfig;
        final MediaItem item = mItem;

        // Special case for non-MediaStore content URIs, do not cache the
        // thumbnail.
        String uriString = item.mContentUri;
        if (uriString != null) {
            Uri uri = Uri.parse(uriString);
            if (uri.getScheme().equals("content") && !uri.getAuthority().equals("media")) {
                try {
                    return UriTexture.createFromUri(mContext, item.mThumbnailUri, 128, 128, 0, null);
                } catch (IOException e) {
                    return null;
                } catch (URISyntaxException e) {
                    return null;
                }
            }
        }

        // Look up the thumbnail in the disk cache.
        if (config == null) {
            Bitmap retVal = null;
            try {
                if (mItem.getMediaType() == MediaItem.MEDIA_TYPE_IMAGE) {
                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
                    try {
                        // We first dirty the cache if the timestamp has changed
                        DiskCache cache = null;
                        MediaSet parentMediaSet = item.mParentMediaSet;
                        if (parentMediaSet != null && parentMediaSet.mDataSource != null) {
                            cache = parentMediaSet.mDataSource.getThumbnailCache();
                            if (cache == LocalDataSource.sThumbnailCache) {
                                if (item.mMimeType != null && item.mMimeType.contains("video")) {
                                    cache = LocalDataSource.sThumbnailCacheVideo;
                                }
                                final long crc64 = Utils.Crc64Long(item.mFilePath);
                                if (!cache.isDataAvailable(crc64, item.mDateModifiedInSec * 1000)) {
                                    UriTexture.invalidateCache(crc64, UriTexture.MAX_RESOLUTION);
                                }
                            }
                        }
                        retVal = UriTexture.createFromUri(mContext, mItem.mContentUri, UriTexture.MAX_RESOLUTION,
                                UriTexture.MAX_RESOLUTION, Utils.Crc64Long(item.mFilePath), null);
                    } catch (IOException e) {
                        ;
                    } catch (URISyntaxException e) {
                        ;
                    }
                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
                } else {
                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
                    new Thread() {
                        public void run() {
                            try {
                                Thread.sleep(5000);
                            } catch (InterruptedException e) {
                                ;
                            }
                            try {
                                MediaStore.Video.Thumbnails.cancelThumbnailRequest(mContext.getContentResolver(), mItem.mId);
                            } catch (Exception e) {
                                ;
                            }
                        }
                    }.start();
                    retVal = MediaStore.Video.Thumbnails.getThumbnail(mContext.getContentResolver(), mItem.mId,
                            MediaStore.Video.Thumbnails.MINI_KIND, null);
                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
                }
            } catch (OutOfMemoryError e) {
                Log.i(TAG, "Bitmap creation fail, outofmemory");
                view.handleLowMemory();
                try {
                    if (!mIsRetrying) {
                        Thread.sleep(1000);
                        mIsRetrying = true;
                        retVal = load(view);
                    }
                } catch (InterruptedException eInterrupted) {

                }
            }
            return retVal;
        } else {
            byte[] data = null;
            MediaSet parentMediaSet = item.mParentMediaSet;
            if (parentMediaSet != null && !parentMediaSet.mIsLocal) {
                DiskCache thumbnailCache = parentMediaSet.mDataSource.getThumbnailCache();
                data = thumbnailCache.get(item.mId, 0);
                if (data == null) {
                    // We need to generate the cache.
                    try {
                        Bitmap retVal = UriTexture.createFromUri(mContext, item.mThumbnailUri, 256, 256, 0, null);
                        data = CacheService.writeBitmapToCache(thumbnailCache, item.mId, item.mId, retVal, config.thumbnailWidth,
                                config.thumbnailHeight, item.mDateModifiedInSec * 1000);
                    } catch (IOException e) {
                        return null;
                    } catch (URISyntaxException e) {
                        return null;
                    }
                }
            } else {
                long dateToUse = (item.mDateAddedInSec > item.mDateModifiedInSec) ? item.mDateAddedInSec : item.mDateModifiedInSec;
                data = CacheService.queryThumbnail(mContext, Utils.Crc64Long(item.mFilePath), item.mId,
                        item.getMediaType() == MediaItem.MEDIA_TYPE_VIDEO, dateToUse * 1000);
            }
            if (data != null) {
                try {
                    // Parse record header.
                    final ByteArrayInputStream cacheInput = new ByteArrayInputStream(data);
                    final DataInputStream dataInput = new DataInputStream(cacheInput);
                    item.mThumbnailId = dataInput.readLong();
                    item.mThumbnailFocusX = dataInput.readShort();
                    item.mThumbnailFocusY = dataInput.readShort();
                    // Decode the thumbnail.
                    final BitmapFactory.Options options = new BitmapFactory.Options();
                    options.inDither = true;
                    options.inScaled = false;
                    options.inPreferredConfig = Bitmap.Config.RGB_565;
                    final Bitmap bitmap = BitmapFactory.decodeByteArray(data, CACHE_HEADER_SIZE, data.length - CACHE_HEADER_SIZE,
                            options);
                    return bitmap;
                } catch (IOException e) {
                    // Fall through to regenerate the cached thumbnail.
                }
            }
        }
        return null;
    }

抱歉!评论已关闭.