out of memory exception + analyzing hprof file dump

老子叫甜甜 提交于 2019-11-30 18:29:55

The idea is to down sample your image so that it looks good on the smaller screen and that you dont have to load the entire bitmap in memory.

1) First get the size of your ImageView/ screen that you will be displaying on.

2) Read the size of you Bitmap by passing in BitmapFactory.Options.inJustDecodeBounds. This will give you the size of the Bitmap rather than loading the entire bitmap.

3) Get a insample size. Calculate the ratio of height and width of the screen to the image height and width. Use the smallest one so that the biggest dimension looks good.

4) Final use the function below to get the down sampled image that wont eat up your memory.

2)(code)

BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmapOptions.inJustDecodeBounds = true;
BitmapFactory.decodeStream(inputStream, null, bitmapOptions);
int imageWidth = bitmapOptions.outWidth;
int imageHeight = bitmapOptions.outHeight;
inputStream.close();

4)(code)

private Bitmap downscaleBitmapUsingDensities(final int sampleSize,final int imageResId)
  {
  final Options bitmapOptions=new Options();
  bitmapOptions.inDensity=sampleSize;
  bitmapOptions.inTargetDensity=1;
  final Bitmap scaledBitmap=BitmapFactory.decodeResource(getResources(),imageResId,bitmapOptions);
  scaledBitmap.setDensity(Bitmap.DENSITY_NONE);
  return scaledBitmap;
  }

Adding largeHeap="true" in your manifest may help. This will allow your application to use more memory.

See: http://developer.android.com/guide/topics/manifest/application-element.html

try the below code:

Resources res = getContext().getResources();
int id = R.drawable.image; 
Bitmap b = BitmapFactory.decodeResource(res, id);    
_img .setimagebitmap(b);

Normally when i get this kind of exception on low Ram devices it's because i have some kind of image to expensive (many kb) for this resolution. I had a weird problem because i just used xhdpi and hdpi drawables directories, on mdpi or even ldpi devices the hdpi conversion to the right resolution raise this exception because cannot resize the image.

It's happens on any device? Could you check you have a specific graphics for this low devices?

Any way with HPOF file you can see what kind of object or at least, wich activity/view has the problem. You need to analyze all this data (there is no a master plan to find the resource it's collapsing your app) to see which has the problem.

Hope this helps, any question, please feel free to ask.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!