Bootstrap

大Bitmap导致Android-java.lang.OutOfMemoryError

问题描述

Android:java.lang.OutOfMemoryError: Failed to allocate a 23970828 byte allocation with 2097152 free bytes and 2MB until OOM

这个错误一般出现在:

当我们在XML文件中使用 android:src="@drawable/launch_bg" 配置资源图片属性时,如果使用了一个高分辨率的图片,那么在程序运行时就会OOM
或者在代码中动态加载展示一个超大的 Bitmap 时出现。

解决方案:

1. 对于Bitmap展示图片之前,应当先对图片进行尺寸压缩!

2. 在AndroidManifest.xml中配置,为App申请更多内存。

	OutOfMemoryError is the most common problem occured in android while especially dealing with bitmaps. This error is thrown by the Java Virtual Machine (JVM) when an object cannot be allocated due to lack of memory space and also, the garbage collector cannot free some space.

	As mentioned by Aleksey, you can add below entities in your manifest file android:hardwareAccelerated="false" , android:largeHeap="true" it will work for some environment's.

		<application
		    android:allowBackup="true"
		    android:hardwareAccelerated="false"
		    android:icon="@mipmap/ic_launcher"
		    android:label="@string/app_name"
		    android:largeHeap="true"
		    android:supportsRtl="true"
		    android:theme="@style/AppTheme">

3. Resize your image before setup to ImageView like this:

	Bitmap.createScaledBitmap(_yourImageBitmap, _size, _size, false);
	where size is actual size of ImageView. You can reach size by measuring:

	```java
		imageView.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
	```
	
	and use next size imageView.getMeasuredWidth() and imageView.getMeasuredHeight() for scaling.

4. 如果用得上 Glide 框架

	Use Glide Library and Override size to less size;

	```java
		Glide.with(mContext).load(imgID).asBitmap().override(1080, 600).into(mImageView);
	```
;