Yesterday encounter this problem is from an input stream call BitmapFactory. DecodeStream (enclosing getContentResolver () openInputStream (uri) get a bitmap at fault. The first call is fine, the second call again will report the above memory overflow problem. And some phones report and some phones do not report. After studying for half a day, it was finally solved. Firstly, the reason is that the memory occupied by the image exceeds the maximum limit of the system virtual machine. Different phones may have different maximum allocations. The solution was to set bitmapFactory.options.

BitmapFactory.Options bitmapOptions = new BitmapFactory.Options(); bitmapOptions.inSampleSize = 4; bitmap = BitmapFactory.decodeStream(this.getContentResolver().. openInputStream(uri), null , bitmapOptions);Copy the code

 

Some said with bitmapOptions inJustDecodeBounds = true; But when I add it, I get a null bitmap. You can get rid of it. Follow the above method to solve the problem. It’s best to recycle bitmaps when they’re not in use:

if (bitmap ! = null && ! bitmap.isRecycled()) bitmap.recycle();Copy the code

Image memory algorithm: introduce the image memory algorithm of the process. The basic class for handling images in Android is Bitmap, which, as the name suggests, is a Bitmap. The memory usage algorithm is as follows: widthheightConfig for the image. If the Config is set to ARGB_8888, then the above Config is 4. A 480320 image takes up 480320*4 bytes of memory. In fact, the default memory usage of android processes is 16M, because Bitmap in addition to Java data, the underlying C++ skia graphics library also holds a SKBitmap object, so it is recommended that the memory usage of images should not exceed 8M. This can be adjusted, and you can set parameters when compiling the source code.

 // Eliminate extra GCs during startup by setting the initial heap size to 4MB.
 // TODO: We should restore the old heap size once the activity reaches the idle state
 VMRuntime.getRuntime().setMinimumHeapSize(INITIAL_HEAP_SIZE);
Copy the code