OutOfMemoryError虽然vm有足够的可用内存

时间:2013-12-09 13:41:36

标签: android android-memory

虽然dalvikvm报告了足够的堆空间,但我发现了这种奇怪的OutOfMemoryError。日志:

12-09 14:16:05.527: D/dalvikvm(10040): GC_FOR_ALLOC freed 551K, 21% free 38000K/47687K, paused 173ms, total 173ms
12-09 14:16:05.527: I/dalvikvm-heap(10040): Grow heap (frag case) to 38.369MB for 858416-byte allocation
12-09 14:16:05.699: D/dalvikvm(10040): GC_FOR_ALLOC freed 6K, 21% free 38832K/48583K, paused 169ms, total 169ms
12-09 14:16:05.894: D/dalvikvm(10040): GC_FOR_ALLOC freed 103K, 20% free 38929K/48583K, paused 169ms, total 169ms
12-09 14:16:05.894: I/dalvikvm-heap(10040): Forcing collection of SoftReferences for 858416-byte allocation
12-09 14:16:06.074: D/dalvikvm(10040): GC_BEFORE_OOM freed 6K, 20% free 38922K/48583K, paused 182ms, total 182ms
12-09 14:16:06.074: E/dalvikvm-heap(10040): Out of memory on a 858416-byte allocation.
12-09 14:16:06.074: I/dalvikvm(10040): "AsyncTask #2" prio=5 tid=17 RUNNABLE
12-09 14:16:06.074: I/dalvikvm(10040):   | group="main" sCount=0 dsCount=0 obj=0x42013580 self=0x5f2a48d8
12-09 14:16:06.074: I/dalvikvm(10040):   | sysTid=10101 nice=10 sched=0/0 cgrp=apps/bg_non_interactive handle=1591062136
12-09 14:16:06.074: I/dalvikvm(10040):   | schedstat=( 7305663992 4216491759 5326 ) utm=697 stm=32 core=1
12-09 14:16:06.074: I/dalvikvm(10040):   at android.graphics.BitmapFactory.nativeDecodeStream(Native Method)
12-09 14:16:06.074: I/dalvikvm(10040):   at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:619)
12-09 14:16:06.074: I/dalvikvm(10040):   at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:691)

正如你在outofmemory发生之前所见,dalvikvm在gc之后报告了大约10mb的空闲内存。分配用于800k位图。我怀疑gc和位图解码之间存在竞争条件,因为报告的dalvik可用内存在崩溃前的最后20-30秒的所有日志语句中都没有降到8mb以下。

问题出现在运行Android 4.1.2的三星Galaxy Tab 2 10.1上。 我正在使用Google I / O应用程序(2012)中的ImageFetcher类的修改版本,所以在加载图像以优化sampleSize选项时,我已经在使用像inJustDecodeBounds这样的东西了。

根据Managing Bitmap Memory中的文档,Android在dalvik堆中分配了位图像素数据(自Android 3.0起),所以为什么解码位图会导致内存占用10mb可用内存

有没有人见过这个或者可能知道发生了什么?

编辑: 每个请求here是来自Google I / O应用2012的图片加载代码。 在我的应用程序中,我只是致电

mImageFetcher.loadImage(myUrl, myImageView);

EDIT2: 从上面的链接中提取的相关图像解码方法,以明确我已经在使用样本大小优化:

public static Bitmap decodeSampledBitmapFromDescriptor(
        FileDescriptor fileDescriptor, int reqWidth, int reqHeight) {

    // First decode with inJustDecodeBounds=true to check dimensions
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFileDescriptor(fileDescriptor, null, options);

    // Calculate inSampleSize
    options.inSampleSize = calculateInSampleSize(options, reqWidth,
            reqHeight);

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;
    return BitmapFactory
            .decodeFileDescriptor(fileDescriptor, null, options);
}

public static int calculateInSampleSize(BitmapFactory.Options options,
        int reqWidth, int reqHeight) {
    // Raw height and width of image
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;

    if (height > reqHeight || width > reqWidth) {
        // Calculate ratios of height and width to requested height and
        // width
        final int heightRatio = Math.round((float) height
                / (float) reqHeight);
        final int widthRatio = Math.round((float) width / (float) reqWidth);

        // Choose the smallest ratio as inSampleSize value, this will
        // guarantee
        // a final image with both dimensions larger than or equal to the
        // requested height and width.
        inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;

        // This offers some additional logic in case the image has a strange
        // aspect ratio. For example, a panorama may have a much larger
        // width than height. In these cases the total pixels might still
        // end up being too large to fit comfortably in memory, so we should
        // be more aggressive with sample down the image (=larger
        // inSampleSize).

        final float totalPixels = width * height;

        // Anything more than 2x the requested pixels we'll sample down
        // further.
        final float totalReqPixelsCap = reqWidth * reqHeight * 2;

        while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) {
            inSampleSize++;
        }
    }
    return inSampleSize;
}

7 个答案:

答案 0 :(得分:4)

关于OutOfMemory(OOM)在你有10 Mb空闲时分配~850000字节,这肯定是由于内存碎片造成的,不能保证堆有一个大于850000字节的连续内存块这就是你的原因所在得到OOM。

看起来很奇怪你仍然得到错误,你似乎已经做了一些优化,你真的释放了你拥有的所有内存吗?我的意思是你有38 Mb使用堆,该内存中包含什么?

您是否尝试过查看图片加载库,例如picasso

在哪里可以这样: Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").fit().into(imageView);

(这会下载并缓存图像并适合并绘制成一个imageView,整洁!)

<强>更新

  1. 您应该在MAT中分析您的hprof文件(应该在root sdcard路径上可用,因为您有一个OOM)以查看您是否持有不必要的引用
  2. 释放这些引用(将它们归零以让GC收集它们)
  3. 使用inBitmap重用内存(在KitKat中变得更强大,图像不需要与之前的图像大小相同,只需保存比以前更多或更少的内存)
  4. 如果您经常要求使用相同的图片,请考虑使用例如LruCache
  5. 如果它们是非常大的位图,请尝试平铺图像(将小方块位图加载到一个大图像中),看看:TileImageView(这是使用GlView进行绘制..)

答案 1 :(得分:3)

似乎ICS和更高版本的Android版本不允许您的VM达到堆的总大小。我在我的应用程序中看到了同样的事情,

您可以添加

android:largeHeap="true" 

到你的&lt; application&gt;这为你的应用程序提供了更大的堆。不好但是有效...

答案 2 :(得分:1)

试试这个

public static Bitmap decodeFile(File f,int WIDTH,int HIGHT){
        try {
            //Decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(new FileInputStream(f),null,o);

            //The new size we want to scale to
            final int REQUIRED_WIDTH=WIDTH;
            final int REQUIRED_HIGHT=HIGHT;
            //Find the correct scale value. It should be the power of 2.
            int scale=1;
            while(o.outWidth/scale/2>=REQUIRED_WIDTH && o.outHeight/scale/2>=REQUIRED_HIGHT)
                scale*=2;

            //Decode with inSampleSize
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize=scale;
            return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
        }
            catch (FileNotFoundException e) {}
        return null;
    }

这将根据您传递的宽度和高度缩放位图。此功能可根据图像分辨率找到正确的比例。

答案 3 :(得分:0)

此代码将为您提供帮助,请尝试此操作

public Bitmap decodeSampledBitmapFromResource(String path,
        int reqWidth, int reqHeight) {

    // First decode with inJustDecodeBounds=true to check dimensions
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(path, options);
    // BitmapFactory.decodeResource(getResources(), id)
    // Calculate inSampleSize
    options.inSampleSize = calculateInSampleSize(options, reqWidth,
            reqHeight);

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;
    return BitmapFactory.decodeFile(path, options);
}

public int calculateInSampleSize(BitmapFactory.Options options,
        int reqWidth, int reqHeight) {
    // Raw height and width of image
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;

    if (height > reqHeight || width > reqWidth) {

        // Calculate ratios of height and width to requested height and
        // width
        final int heightRatio = Math.round((float) height
                / (float) reqHeight);
        final int widthRatio = Math.round((float) width / (float) reqWidth);

        // Choose the smallest ratio as inSampleSize value, this will
        // guarantee
        // a final image with both dimensions larger than or equal to the
        // requested height and width.
        inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
    }

    return inSampleSize;
}

答案 4 :(得分:0)

我是新手我不确定但是尝试像这样采样图像

  final BitmapFactory.Options options = new BitmapFactory.Options();
  options.inSampleSize = 8;

  Bitmap bm=BitmapFactory.decodeFile(strPath,options);

使用inSampleSize将位图加载到内存。对inSampleSize值使用2的幂对于解码器来说更快且更有效。但是,如果您计划将已调整大小的版本缓存在内存或磁盘上,通常仍需要解码到最合适的图像尺寸以节省空间。

答案 5 :(得分:0)

创建Imageloader类

package com.example.model;

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.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.widget.ImageView;

public class ImageLoader {

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

    public ImageLoader(Context context){
        fileCache=new FileCache(context);
        executorService=Executors.newFixedThreadPool(5);
    }

    final int stub_id=R.drawable.load;
    public void DisplayImage(String url, ImageView imageView)
    {
        imageViews.put(imageView, url);
        Bitmap bitmap=memoryCache.get(url);
        if(bitmap!=null)
            imageView.setImageBitmap(bitmap);
        else
        {
            queuePhoto(url, imageView);
            imageView.setImageResource(stub_id);
        }
    }

    private void queuePhoto(String url, ImageView imageView)
    {
        PhotoToLoad p=new PhotoToLoad(url, imageView);
        executorService.submit(new PhotosLoader(p));
    }

    private 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);
           // System.out.println("url :"+imageUrl);
            HttpURLConnection conn = (HttpURLConnection)imageUrl.openConnection();
            conn.setConnectTimeout(30000);
            conn.setReadTimeout(30000);
            conn.setInstanceFollowRedirects(true);

            InputStream is=conn.getInputStream();
            OutputStream os = new FileOutputStream(f);
            Utils.CopyStream(is, os);

            os.close();
            bitmap = decodeFile(f);


            return bitmap;
        } catch (Throwable ex){
           ex.printStackTrace();
           if(ex instanceof OutOfMemoryError)
               memoryCache.clear();
           return null;
        }
    }

    //decodes image and scales it to reduce memory consumption
    private Bitmap decodeFile(File f){
        try {
            //decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            o.inPurgeable = true; // Tell to garbage collector that whether it needs free memory, the Bitmap can be cleared
            o.inTempStorage = new byte[32 * 1024];
            BitmapFactory.decodeStream(new FileInputStream(f),null,o);

            //Find the correct scale value. It should be the power of 2.
            final int REQUIRED_SIZE=70;
            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;
                long heapSize = Runtime.getRuntime().maxMemory();

               long heapsize1=(heapSize/(1024*1024));
               if(heapsize1>95)
               {
                  scale*=1;
                 // System.out.println("scale1 :");
               }else if(heapsize1>63 && heapsize1<=95){
                  scale*=2;
                // System.out.println("scale2 :");
               }else if(heapsize1>31 && heapsize1<=63){
                   scale*=2;
                 // System.out.println("scale22 :");
               }else if(heapsize1>0 && heapsize1<=31){
                      scale*=2;
                    // System.out.println("scale23 :");
                   }
               /*else if(heapsize1>31 && heapsize1<=63){
                  scale*=2;
                // System.out.println("scale2 :");
               }else if(heapsize1>0 && heapsize1<=31){
                  scale*=2;
                    // System.out.println("scale2 :");
                   }*/

            }

            //decode with inSampleSize
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inPurgeable = true; // Tell to garbage collector that whether it needs free memory, the Bitmap can be cleared
            o2.inTempStorage = new byte[32 * 1024];
            o2.inSampleSize=scale;
            Bitmap bitmap1=BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
          //  System.out.println("width : "+bitmap1.getWidth()+ " height : "+bitmap1.getHeight());
       /*     if(bitmap1.getHeight()>=bitmap1.getWidth())
            {

                bitmap1 = Bitmap.createScaledBitmap(bitmap1, bitmap1.getHeight(),bitmap1.getWidth(), true);
            }else{
                //bmp = Bitmap.createScaledBitmap(bmp, (int) height2,width, true);
                Matrix matrix = new Matrix();

                matrix.postRotate(270);
                bitmap1 = Bitmap.createBitmap(bitmap1 , 0, 0, bitmap1 .getWidth(), bitmap1 .getHeight(), matrix, true);

            }*/
            return bitmap1;
        } catch (FileNotFoundException e) {}
        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;
        }
    }

    class PhotosLoader implements Runnable {
        PhotoToLoad photoToLoad;
        PhotosLoader(PhotoToLoad photoToLoad){
            this.photoToLoad=photoToLoad;
        }

        @Override
        public void run() {
            if(imageViewReused(photoToLoad))
                return;
            Bitmap bmp=getBitmap(photoToLoad.url);
            memoryCache.put(photoToLoad.url, bmp);
            if(imageViewReused(photoToLoad))
                return;
            BitmapDisplayer bd=new BitmapDisplayer(bmp, photoToLoad);
            Activity a=(Activity)photoToLoad.imageView.getContext();
            a.runOnUiThread(bd);
        }
    }

    boolean imageViewReused(PhotoToLoad photoToLoad){
        String tag=imageViews.get(photoToLoad.imageView);
        if(tag==null || !tag.equals(photoToLoad.url))
            return true;
        return false;
    }

    //Used to display bitmap in the UI thread
    class BitmapDisplayer implements Runnable
    {
        Bitmap bitmap;
        PhotoToLoad photoToLoad;
        public BitmapDisplayer(Bitmap b, PhotoToLoad p){
            bitmap=b;photoToLoad=p;
            }
        public void run()
        {
            if(imageViewReused(photoToLoad))
                return;
            if(bitmap!=null)
                photoToLoad.imageView.setImageBitmap(bitmap);
            else
                photoToLoad.imageView.setImageResource(stub_id);
        }
    }

    public void clearCache() {
        memoryCache.clear();
        fileCache.clear();
    }

}

使用

或使用该链接lazy loader example

答案 6 :(得分:0)

首先,所有答案都可以帮助您降低内存消耗,但我们中没有人可以真正帮助您的应用程序,因为我们不知道整个代码。

我将与您分享我对我们的应用程序的体验。我们遇到了太多的OOM,我们尝试过Android中的Picasso,BitmapFun示例,最后我决定对我的应用进行分析。

Android Studio为您提供了一个名为Monitor的工具,您可以在其中跟踪您的App在您调用的每个Activity中,每次轮换中在RAM中分配的内存量等。

您可以使用HEAP Dump导出刚刚完成的分析,然后将其导入Eclipse Memory Analyzer Tool。在那里你可以运行一个对象泄漏检测器(或类似的东西。它将帮助你显示哪些对象泄漏在RAM中。

即。我们使用旧方法(OnRetainCustomConfig ...),您可以在其中存储对象的引用。问题是新的Activity接收了旧Activity的Object的引用,因此,GC没有清除成功的旧活动,因为它认为它们仍在使用中。

我希望我的评论可以帮助你