关于解决android图片设置时outofmemery的问题!!!!!!!!!!
2013-06-16 22:17
393 查看
一, 豆丁文档:
http://www.docin.com/p-239547289.html
二, Android Out Of Memory(OOM) 的详细研究
基于Android开发多媒体和游戏应用时,可能会挺经常出现Out Of Memory 异常 ,顾名思义这个异常是说你的内存不够用或者耗尽了。
在Android中,一个Process 只能使用16M内存,如果超过了这个限制就会跳出这个异常。这样就要求我们要时刻想着释放资源。Java的回收工作是交给GC的,如何让GC能及时的回收已经不是用的对象,这个里面有很多技巧,大家可以google一下。
因为总内存的使用超过16M而导致OOM的情况,非常简单,我就不继续展开说。值得注意的是Bitmap在不用时,一定要recycle,不然OOM是非常容易出现的。
本文想跟大家一起讨论的是另一种情况:明明还有很多内存,但是发生OOM了。
这种情况经常出现在生成Bitmap的时候。有兴趣的可以试一下,在一个函数里生成一个13m 的int数组。
再该函数结束后,按理说这个int数组应该已经被释放了,或者说可以释放,这个13M的空间应该可以空出来,
这个时候如果你继续生成一个10M的int数组是没有问题的,反而生成一个4M的Bitmap就会跳出OOM。这个就奇怪了,为什么10M的int够空间,反而4M的Bitmap不够呢?
这个问题困扰很久,在网上,国外各大论坛搜索了很久,一般关于OOM的解释和解决方法都是,如何让GC尽快回收的代码风格之类,并没有实际的支出上述情况的根源。
直到昨天在一个老外的blog上终于看到了这方面的解释,我理解后归纳如下:
在Android中:
1.一个进程的内存可以由2个部分组成:java 使用内存 ,C 使用内存 ,这两个内存的和必须小于16M,不然就会出现大家熟悉的OOM,这个就是第一种OOM的情况。
2.更加奇怪的是这个:一旦内存分配给Java后,以后这块内存即使释放后,也只能给Java的使用,这个估计跟java虚拟机里把内存分成好几块进行缓存的原因有关,反正C就别想用到这块的内存了,所以如果Java突然占用了一个大块内存,即使很快释放了:
C能使用的内存 = 16M - Java某一瞬间占用的最大内存。
而Bitmap的生成是通过malloc进行内存分配的,占用的是C的内存,这个也就说明了,上述的4MBitmap无法生成的原因,因为在13M被Java用过后,剩下C能用的只有3M了。
下面是我参考的blog的所有内容:
[android-developers] Re: OOM error caught bei DefaultException
handler ... but there is plenty of memory
内如如下:
> You might try to pre-allocate bitmap memory before launching the WebViews?It's not the WebView that's triggering the OOM, but some arbitrary otherpiece of code that needs memory that is not *there* anymore. Very often thisis happening when starting a new
activity.
Ok, I see, I have to start dealing with automating my apology.
There is one more, small thing that I can do. I also do some downloading andXML parsing in the background at times. This only takes Java Heap (<3MB),but maybe I should move that stuff to a separate process. This may lower thechances of an OOM. I'll think about
it, but with all the added complexity ofinter process communication I am not sure I would want to go there.
Anyway, thanks for sharing your insights. That was very helpful.
On Wed, Oct 7, 2009 at 10:48 PM, Tom Gibara <[EMAIL PROTECTED]> wrote:
> I think it's better to add a couple more columns to the table to see the
> picture (as I see it) more clearly:> JH = Java Heap
> JU = Memory actually used by Java
> NH = Native Heap
> TU = Total memory Used = JU + NH
> TA = Total memory Allocated = JH + NH
>
> (note I'm not distinguishing between native heap and native heap used
> because it's not relevant here)
>
> The system requires TA (the process size as you called it) to not exceed
> 16MB, the evolution is:
>
> JU JH NH TU TA
> 1) 2 2 0 2 2
> 2) 4 4 0 4 4
> 3) 4 4 2 6 6
> 4) 14 14 2 16 16
> 5) 4 14 2 6 16
> 6) 4 14 4 10 18 *** OH NO! ***
>
> The key is what happens between (4) and (5): GC reclaims 10MB (JU reduced> by 10MB) but the java heap doesn't shrink (JH stays at 14MB). This enlarged > java heap basically squeezes the maximum native heap allocation.
>
> The simplest approach is to try and ensure that your application maintains
> a 'flatish' memory profile - no big spikes. You should do this anyway, since
> it means that your application is being well behaved and won't force other
> apps to be terminated just because your application needs a temporary shot> of memory (which will then remain as a glut until the application restarts).
>
> As you point out, WebViews are heavy on memory usage, and these might be
> what's causing your memory usage to spike. I don't have any good suggestions
> for a fix. You might try to pre-allocate bitmap memory before launching the
> WebViews? It might work, but it may be complicated to do and could cause
> OOMs when WebViews are instantiated - no way around that, your application
> is simply using too much memory at that point.
>
三,android 加载图片轻松避免OOM(out of memory)
在使用android加载图片的时候,经常会出现内存溢出,主要是由于android可使用的内存太小,而通过代码加载进来的图片,并不会被GC回收,于是我写了一个工具类用来加载图片,并且建立缓存,轻松避免内存溢出,废话不多说,上代码
[java] view
plaincopy
package l.test1.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
/**
* Bitmap工具类,缓存用过的指定数量的图片,使用此工具类,不再需要手动管理Bitmap内存 原理:
* 用一个队列保存使用Bitmap的顺序,每次使用Bitmap将对象移动到队列头 当内存不够,或者达到制定的缓存数量的时候,回收队列尾部图片
* 保证当前使用最多的图片得到最长时间的缓存,提高速度
*
* @author liaoxingliao
*
*/
public final class BitMapUtil {
private static final Size ZERO_SIZE = new Size(0, 0);
private static final Options OPTIONS_GET_SIZE = new Options();
private static final Options OPTIONS_DECODE = new Options();
private static final byte[] LOCKED = new byte[0];
private static final LinkedList<String> CACHE_ENTRIES = new LinkedList<String>(); // 此对象用来保持Bitmap的回收顺序,保证最后使用的图片被回收
private static final Queue<QueueEntry> TASK_QUEUE = new LinkedList<QueueEntry>(); // 线程请求创建图片的队列
private static final Set<String> TASK_QUEUE_INDEX = new HashSet<String>(); // 保存队列中正在处理的图片的key,有效防止重复添加到请求创建队列
private static final Map<String, Bitmap> IMG_CACHE_INDEX = new HashMap<String, Bitmap>(); // 缓存Bitmap
// 通过图片路径,图片大小
private static int CACHE_SIZE = 200; // 缓存图片数量
static {
OPTIONS_GET_SIZE.inJustDecodeBounds = true;
// 初始化创建图片线程,并等待处理
new Thread() {
{
setDaemon(true);
}
public void run() {
while (true) {
synchronized (TASK_QUEUE) {
if (TASK_QUEUE.isEmpty()) {
try {
TASK_QUEUE.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
QueueEntry entry = TASK_QUEUE.poll();
String key = createKey(entry.path, entry.width,
entry.height);
TASK_QUEUE_INDEX.remove(key);
//createBitmap(entry.path, entry.width, entry.height);
//修正过的代码
getBitmap(entry.path,entry.width,entry.height);
}
}
}.start();
}
/**
* 创建一张图片 如果缓存中已经存在,则返回缓存中的图,否则创建一个新的对象,并加入缓存
* 宽度,高度,为了缩放原图减少内存的,如果输入的宽,高,比原图大,返回原图
*
* @param path 图片物理路径 (必须是本地路径,不能是网络路径)
* @param width 需要的宽度
* @param height 需要的高度
* @return
*/
public static Bitmap getBitmap(String path, int width, int height) {
Bitmap bitMap = null;
try {
if (CACHE_ENTRIES.size() >= CACHE_SIZE) {
destoryLast();
}
bitMap = useBitmap(path, width, height);
if (bitMap != null && !bitMap.isRecycled()) {
return bitMap;
}
bitMap = createBitmap(path, width, height);
String key = createKey(path, width, height);
synchronized (LOCKED) {
IMG_CACHE_INDEX.put(key, bitMap);
CACHE_ENTRIES.addFirst(key);
}
} catch (OutOfMemoryError err) {
destoryLast();
System.out.println(CACHE_SIZE);
//return createBitmap(path, width, height);
//修正过的代码
return getBitmap(path, width, height);
}
return bitMap;
}
/**
* 设置缓存图片数量 如果输入负数,会产生异常
*
* @param size
*/
public static void setCacheSize(int size) {
if (size <= 0) {
throw new RuntimeException("size :" + size);
}
while (size < CACHE_ENTRIES.size()) {
destoryLast();
}
CACHE_SIZE = size;
}
/**
* 加入一个图片处理请求到图片创建队列
*
* @param path
* 图片路径(本地)
* @param width
* 图片宽度
* @param height
* 图片高度
*/
public static void addTask(String path, int width, int height) {
QueueEntry entry = new QueueEntry();
entry.path = path;
entry.width = width;
entry.height = height;
synchronized (TASK_QUEUE) {
String key = createKey(path, width, height);
if (!TASK_QUEUE_INDEX.contains(key)
&& !IMG_CACHE_INDEX.containsKey(key)) {
TASK_QUEUE.add(entry);
TASK_QUEUE_INDEX.add(key);
TASK_QUEUE.notify();
}
}
}
/**
* 通过图片路径返回图片实际大小
* @param path 图片物理路径
* @return
*/
public static Size getBitMapSize(String path) {
File file = new File(path);
if (file.exists()) {
InputStream in = null;
try {
in = new FileInputStream(file);
BitmapFactory.decodeStream(in, null, OPTIONS_GET_SIZE);
return new Size(OPTIONS_GET_SIZE.outWidth,
OPTIONS_GET_SIZE.outHeight);
} catch (FileNotFoundException e) {
return ZERO_SIZE;
} finally {
closeInputStream(in);
}
}
return ZERO_SIZE;
}
// ------------------------------------------------------------------ private Methods
// 将图片加入队列头
private static Bitmap useBitmap(String path, int width, int height) {
Bitmap bitMap = null;
String key = createKey(path, width, height);
synchronized (LOCKED) {
bitMap = IMG_CACHE_INDEX.get(key);
if (null != bitMap) {
if (CACHE_ENTRIES.remove(key)) {
CACHE_ENTRIES.addFirst(key);
}
}
}
return bitMap;
}
// 回收最后一张图片
private static void destoryLast() {
synchronized (LOCKED) {
String key = CACHE_ENTRIES.removeLast();
if (key.length() > 0) {
Bitmap bitMap = IMG_CACHE_INDEX.remove(key);
if (bitMap != null && !bitMap.isRecycled()) {
bitMap.recycle();
bitMap = null;
}
}
}
}
// 创建键
private static String createKey(String path, int width, int height) {
if (null == path || path.length() == 0) {
return "";
}
return path + "_" + width + "_" + height;
}
// 通过图片路径,宽度高度创建一个Bitmap对象
private static Bitmap createBitmap(String path, int width, int height) {
File file = new File(path);
if (file.exists()) {
InputStream in = null;
try {
in = new FileInputStream(file);
Size size = getBitMapSize(path);
if (size.equals(ZERO_SIZE)) {
return null;
}
int scale = 1;
int a = size.getWidth() / width;
int b = size.getHeight() / height;
scale = Math.max(a, b);
synchronized (OPTIONS_DECODE) {
OPTIONS_DECODE.inSampleSize = scale;
Bitmap bitMap = BitmapFactory.decodeStream(in, null,
OPTIONS_DECODE);
return bitMap;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
closeInputStream(in);
}
}
return null;
}
// 关闭输入流
private static void closeInputStream(InputStream in) {
if (null != in) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
// 图片大小
static class Size {
private int width, height;
Size(int width, int height) {
this.width = width;
this.height = height;
}
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
}
// 队列缓存参数对象
static class QueueEntry {
public String path;
public int width;
public int height;
}
}
测试代码使用android1.6完成,需要的可移步下载,地址为:http://download.csdn.net/detail/liaoxingliao/3756187 (这个工程内部的这个工具类由于我的疏忽有几个地方写错了,现在但是那个资源上传完以后,既不能修改,又不能删除.有谁知道怎么改的,希望告诉我一下)
四,
尽量不要使用setImageBitmap或setImageResource或BitmapFactory.decodeResource来设置一张大图,
因为这些函数在完成decode后,最终都是通过java层的createBitmap来完成的,需要消耗更多内存。
因此,改用先通过BitmapFactory.decodeStream方法,创建出一个bitmap,再将其设为ImageView的 source,
decodeStream最大的秘密在于其直接调用JNI>>nativeDecodeAsset()来完成decode,
无需再使用java层的createBitmap,从而节省了java层的空间。
如果在读取时加上图片的Config参数,可以跟有效减少加载的内存,从而跟有效阻止抛out of Memory异常
另外,decodeStream直接拿的图片来读取字节码了, 不会根据机器的各种分辨率来自动适应,
使用了decodeStream之后,需要在hdpi和mdpi,ldpi中配置相应的图片资源,
否则在不同分辨率机器上都是同样大小(像素点数量),显示出来的大小就不对了。
另外,以下方式也大有帮助:
1. InputStream is = this.getResources().openRawResource(R.drawable.pic1);
BitmapFactory.Options options=new BitmapFactory.Options();
options.inJustDecodeBounds = false;
options.inSampleSize = 10; //width,hight设为原来的十分一
Bitmap btp =BitmapFactory.decodeStream(is,null,options);
2. if(!bmp.isRecycle() ){
bmp.recycle() //回收图片所占的内存
system.gc() //提醒系统及时回收
}
以下奉上一个方法:
Java代码
1. /**
2. * 以最省内存的方式读取本地资源的图片
3. * @param context
4. * @param resId
5. * @return
6. */
7. public static Bitmap readBitMap(Context context, int resId){
8. BitmapFactory.Options opt = new BitmapFactory.Options();
9. opt.inPreferredConfig = Bitmap.Config.RGB_565;
10. opt.inPurgeable = true;
11. opt.inInputShareable = true;
12. //获取资源图片
13. InputStream is = context.getResources().openRawResource(resId);
14. return BitmapFactory.decodeStream(is,null,opt);
15. }
================================================================================
Android内存溢出的解决办法
转自:http://www.cppblog.com/iuranus/archive/2010/11/15/124394.html?opt=admin
昨天在模拟器上给gallery放入图片的时候,出现java.lang.OutOfMemoryError: bitmap size exceeds VM budget 异常,图像大小超过了RAM内存。
模拟器RAM比较小,只有8M内存,当我放入的大量的图片(每个100多K左右),就出现上面的原因。
由于每张图片先前是压缩的情况,放入到Bitmap的时候,大小会变大,导致超出RAM内存,具体解决办法如下:
//解决加载图片 内存溢出的问题
//Options 只保存图片尺寸大小,不保存图片到内存
BitmapFactory.Options opts = new BitmapFactory.Options();
//缩放的比例,缩放是很难按准备的比例进行缩放的,其值表明缩放的倍数,SDK中建议其值是2的指数值,值越大会导致图片不清晰
opts.inSampleSize = 4;
Bitmap bmp = null;
bmp = BitmapFactory.decodeResource(getResources(), mImageIds[position],opts);
...
//回收
bmp.recycle();
通过上面的方式解决了,但是这并不是最完美的解决方式。
通过一些了解,得知如下:
优化Dalvik虚拟机的堆内存分配
对 于Android平台来说,其托管层使用的Dalvik Java VM从目前的表现来看还有很多地方可以优化处理,比如我们在开发一些大型游戏或耗资源的应用中可能考虑手动干涉GC处理,使用 dalvik.system.VMRuntime类提供的setTargetHeapUtilization方法可以增强程序堆内存的处理效率。当然具体 原理我们可以参考开源工程,这里我们仅说下使用方法: private final static float TARGET_HEAP_UTILIZATION = 0.75f; 在程序onCreate时就可以调用
VMRuntime.getRuntime().setTargetHeapUtilization(TARGET_HEAP_UTILIZATION); 即可。
Android堆内存也可自己定义大小
对于一些Android项目,影响性能瓶颈的主要是Android自己内存管理机制问题,目前手机厂商对RAM都比较吝啬,对于软件的流畅性来说RAM对 性能的影响十分敏感,除了 优化Dalvik虚拟机的堆内存分配外,我们还可以强制定义自己软件的对内存大小,我们使用Dalvik提供的 dalvik.system.VMRuntime类来设置最小堆内存为例:
private final static int CWJ_HEAP_SIZE = 6* 1024* 1024 ;
VMRuntime.getRuntime().setMinimumHeapSize(CWJ_HEAP_SIZE); //设置最小heap内存为6MB大小。当然对于内存吃紧来说还可以通过手动干涉GC去处理
bitmap 设置图片尺寸,避免 内存溢出 OutOfMemoryError的优化方法
★android 中用bitmap 时很容易内存溢出,报如下错误:Java.lang.OutOfMemoryError : bitmap size exceeds VM budget
● 主要是加上这段:
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 2;
● eg1:(通过Uri取图片)
private ImageView preview;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 2;//图片宽高都为原来的二分之一,即图片为原来的四分之一
Bitmap bitmap = BitmapFactory.decodeStream(cr
.openInputStream(uri), null, options);
preview.setImageBitmap(bitmap);
以上代码可以优化内存溢出,但它只是改变图片大小,并不能彻底解决内存溢出。
● eg2:(通过路径去图片)
private ImageView preview;
private String fileName= "/sdcard/DCIM/Camera/2010-05-14 16.01.44.jpg";
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 2;//图片宽高都为原来的二分之一,即图片为原来的四分之一
Bitmap b = BitmapFactory.decodeFile(fileName, options);
preview.setImageBitmap(b);
filePath.setText(fileName);
★Android 还有一些性能优化的方法:
● 首先内存方面,可以参考 Android堆内存也可自己定义大小 和 优化Dalvik虚拟机的堆内存分配
● 基础类型上,因为Java没有实际的指针,在敏感运算方面还是要借助NDK来完成。Android123提示游戏开发者,这点比较有意思的是Google 推出NDK可能是帮助游戏开发人员,比如OpenGL ES的支持有明显的改观,本地代码操作图形界面是很必要的。
● 图形对象优化,这里要说的是Android上的Bitmap对象销毁,可以借助recycle()方法显示让GC回收一个Bitmap对象,通常对一个不用的Bitmap可以使用下面的方式,如
if(bitmapObject.isRecycled()==false) //如果没有回收
bitmapObject.recycle();
● 目前系统对动画支持比较弱智对于常规应用的补间过渡效果可以,但是对于游戏而言一般的美工可能习惯了GIF方式的统一处理,目前Android系统仅能预览GIF的第一帧,可以借助J2ME中通过线程和自己写解析器的方式来读取GIF89格式的资源。
● 对于大多数Android手机没有过多的物理按键可能我们需要想象下了做好手势识别 GestureDetector 和重力感应来实现操控。通常我们还要考虑误操作问题的降噪处理。
Android堆内存也可自己定义大小
对于一些大型Android项目或游戏来说在算法处理上没有问题外,影响性能瓶颈的主要是Android自己内存管理机制问题,目前手机厂商对RAM都比 较吝啬,对于软件的流畅性来说RAM对性能的影响十分敏感,除了上次Android开发网提到的 优化Dalvik虚拟机的堆内存分配外,我们还可以强制定义自己软件的对内存大小,我们使用Dalvik提供的 dalvik.system.VMRuntime类来设置最小堆内存为例:
private final static int CWJ_HEAP_SIZE = 6* 1024* 1024 ;
VMRuntime.getRuntime().setMinimumHeapSize(CWJ_HEAP_SIZE); //设置最小heap内存为6MB大小。当然对于内存吃紧来说还可以通过手动干涉GC去处理,我们将在下次提到具体应用。
优化Dalvik虚拟机的堆内存分配
对 于Android平台来说,其托管层使用的Dalvik JavaVM从目前的表现来看还有很多地方可以优化处理,比如我们在开发一些大型游戏或耗资源的应用中可能考虑手动干涉GC处理,使用 dalvik.system.VMRuntime类提供的setTargetHeapUtilization方法可以增强程序堆内存的处理效率。当然具体 原理我们可以参考开源工程,这里我们仅说下使用方法: private final static floatTARGET_HEAP_UTILIZATION = 0.75f; 在程序onCreate时就可以调用
VMRuntime.getRuntime().setTargetHeapUtilization(TARGET_HEAP_UTILIZATION); 即可。
介绍一下图片占用进程的内存算法吧。
android中处理图片的基础类是Bitmap,顾名思义,就是位图。占用内存的算法如下:
图片的width*height*Config。
如果Config设置为ARGB_8888,那么上面的Config就是4。一张480*320的图片占用的内存就是480*320*4 byte。
前面有人说了一下8M的概念,其实是在默认情况下android进程的内存占用量为16M,因为Bitmap他除了java中持有数据外,底层C++的 skia图形库还会持有一个SKBitmap对象,因此一般图片占用内存推荐大小应该不超过8M。这个可以调整,编译源代码时可以设置参数。
http://www.docin.com/p-239547289.html
二, Android Out Of Memory(OOM) 的详细研究
基于Android开发多媒体和游戏应用时,可能会挺经常出现Out Of Memory 异常 ,顾名思义这个异常是说你的内存不够用或者耗尽了。
在Android中,一个Process 只能使用16M内存,如果超过了这个限制就会跳出这个异常。这样就要求我们要时刻想着释放资源。Java的回收工作是交给GC的,如何让GC能及时的回收已经不是用的对象,这个里面有很多技巧,大家可以google一下。
因为总内存的使用超过16M而导致OOM的情况,非常简单,我就不继续展开说。值得注意的是Bitmap在不用时,一定要recycle,不然OOM是非常容易出现的。
本文想跟大家一起讨论的是另一种情况:明明还有很多内存,但是发生OOM了。
这种情况经常出现在生成Bitmap的时候。有兴趣的可以试一下,在一个函数里生成一个13m 的int数组。
再该函数结束后,按理说这个int数组应该已经被释放了,或者说可以释放,这个13M的空间应该可以空出来,
这个时候如果你继续生成一个10M的int数组是没有问题的,反而生成一个4M的Bitmap就会跳出OOM。这个就奇怪了,为什么10M的int够空间,反而4M的Bitmap不够呢?
这个问题困扰很久,在网上,国外各大论坛搜索了很久,一般关于OOM的解释和解决方法都是,如何让GC尽快回收的代码风格之类,并没有实际的支出上述情况的根源。
直到昨天在一个老外的blog上终于看到了这方面的解释,我理解后归纳如下:
在Android中:
1.一个进程的内存可以由2个部分组成:java 使用内存 ,C 使用内存 ,这两个内存的和必须小于16M,不然就会出现大家熟悉的OOM,这个就是第一种OOM的情况。
2.更加奇怪的是这个:一旦内存分配给Java后,以后这块内存即使释放后,也只能给Java的使用,这个估计跟java虚拟机里把内存分成好几块进行缓存的原因有关,反正C就别想用到这块的内存了,所以如果Java突然占用了一个大块内存,即使很快释放了:
C能使用的内存 = 16M - Java某一瞬间占用的最大内存。
而Bitmap的生成是通过malloc进行内存分配的,占用的是C的内存,这个也就说明了,上述的4MBitmap无法生成的原因,因为在13M被Java用过后,剩下C能用的只有3M了。
下面是我参考的blog的所有内容:
[android-developers] Re: OOM error caught bei DefaultException
handler ... but there is plenty of memory
内如如下:
> You might try to pre-allocate bitmap memory before launching the WebViews?It's not the WebView that's triggering the OOM, but some arbitrary otherpiece of code that needs memory that is not *there* anymore. Very often thisis happening when starting a new
activity.
Ok, I see, I have to start dealing with automating my apology.
There is one more, small thing that I can do. I also do some downloading andXML parsing in the background at times. This only takes Java Heap (<3MB),but maybe I should move that stuff to a separate process. This may lower thechances of an OOM. I'll think about
it, but with all the added complexity ofinter process communication I am not sure I would want to go there.
Anyway, thanks for sharing your insights. That was very helpful.
On Wed, Oct 7, 2009 at 10:48 PM, Tom Gibara <[EMAIL PROTECTED]> wrote:
> I think it's better to add a couple more columns to the table to see the
> picture (as I see it) more clearly:> JH = Java Heap
> JU = Memory actually used by Java
> NH = Native Heap
> TU = Total memory Used = JU + NH
> TA = Total memory Allocated = JH + NH
>
> (note I'm not distinguishing between native heap and native heap used
> because it's not relevant here)
>
> The system requires TA (the process size as you called it) to not exceed
> 16MB, the evolution is:
>
> JU JH NH TU TA
> 1) 2 2 0 2 2
> 2) 4 4 0 4 4
> 3) 4 4 2 6 6
> 4) 14 14 2 16 16
> 5) 4 14 2 6 16
> 6) 4 14 4 10 18 *** OH NO! ***
>
> The key is what happens between (4) and (5): GC reclaims 10MB (JU reduced> by 10MB) but the java heap doesn't shrink (JH stays at 14MB). This enlarged > java heap basically squeezes the maximum native heap allocation.
>
> The simplest approach is to try and ensure that your application maintains
> a 'flatish' memory profile - no big spikes. You should do this anyway, since
> it means that your application is being well behaved and won't force other
> apps to be terminated just because your application needs a temporary shot> of memory (which will then remain as a glut until the application restarts).
>
> As you point out, WebViews are heavy on memory usage, and these might be
> what's causing your memory usage to spike. I don't have any good suggestions
> for a fix. You might try to pre-allocate bitmap memory before launching the
> WebViews? It might work, but it may be complicated to do and could cause
> OOMs when WebViews are instantiated - no way around that, your application
> is simply using too much memory at that point.
>
三,android 加载图片轻松避免OOM(out of memory)
在使用android加载图片的时候,经常会出现内存溢出,主要是由于android可使用的内存太小,而通过代码加载进来的图片,并不会被GC回收,于是我写了一个工具类用来加载图片,并且建立缓存,轻松避免内存溢出,废话不多说,上代码
[java] view
plaincopy
package l.test1.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
/**
* Bitmap工具类,缓存用过的指定数量的图片,使用此工具类,不再需要手动管理Bitmap内存 原理:
* 用一个队列保存使用Bitmap的顺序,每次使用Bitmap将对象移动到队列头 当内存不够,或者达到制定的缓存数量的时候,回收队列尾部图片
* 保证当前使用最多的图片得到最长时间的缓存,提高速度
*
* @author liaoxingliao
*
*/
public final class BitMapUtil {
private static final Size ZERO_SIZE = new Size(0, 0);
private static final Options OPTIONS_GET_SIZE = new Options();
private static final Options OPTIONS_DECODE = new Options();
private static final byte[] LOCKED = new byte[0];
private static final LinkedList<String> CACHE_ENTRIES = new LinkedList<String>(); // 此对象用来保持Bitmap的回收顺序,保证最后使用的图片被回收
private static final Queue<QueueEntry> TASK_QUEUE = new LinkedList<QueueEntry>(); // 线程请求创建图片的队列
private static final Set<String> TASK_QUEUE_INDEX = new HashSet<String>(); // 保存队列中正在处理的图片的key,有效防止重复添加到请求创建队列
private static final Map<String, Bitmap> IMG_CACHE_INDEX = new HashMap<String, Bitmap>(); // 缓存Bitmap
// 通过图片路径,图片大小
private static int CACHE_SIZE = 200; // 缓存图片数量
static {
OPTIONS_GET_SIZE.inJustDecodeBounds = true;
// 初始化创建图片线程,并等待处理
new Thread() {
{
setDaemon(true);
}
public void run() {
while (true) {
synchronized (TASK_QUEUE) {
if (TASK_QUEUE.isEmpty()) {
try {
TASK_QUEUE.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
QueueEntry entry = TASK_QUEUE.poll();
String key = createKey(entry.path, entry.width,
entry.height);
TASK_QUEUE_INDEX.remove(key);
//createBitmap(entry.path, entry.width, entry.height);
//修正过的代码
getBitmap(entry.path,entry.width,entry.height);
}
}
}.start();
}
/**
* 创建一张图片 如果缓存中已经存在,则返回缓存中的图,否则创建一个新的对象,并加入缓存
* 宽度,高度,为了缩放原图减少内存的,如果输入的宽,高,比原图大,返回原图
*
* @param path 图片物理路径 (必须是本地路径,不能是网络路径)
* @param width 需要的宽度
* @param height 需要的高度
* @return
*/
public static Bitmap getBitmap(String path, int width, int height) {
Bitmap bitMap = null;
try {
if (CACHE_ENTRIES.size() >= CACHE_SIZE) {
destoryLast();
}
bitMap = useBitmap(path, width, height);
if (bitMap != null && !bitMap.isRecycled()) {
return bitMap;
}
bitMap = createBitmap(path, width, height);
String key = createKey(path, width, height);
synchronized (LOCKED) {
IMG_CACHE_INDEX.put(key, bitMap);
CACHE_ENTRIES.addFirst(key);
}
} catch (OutOfMemoryError err) {
destoryLast();
System.out.println(CACHE_SIZE);
//return createBitmap(path, width, height);
//修正过的代码
return getBitmap(path, width, height);
}
return bitMap;
}
/**
* 设置缓存图片数量 如果输入负数,会产生异常
*
* @param size
*/
public static void setCacheSize(int size) {
if (size <= 0) {
throw new RuntimeException("size :" + size);
}
while (size < CACHE_ENTRIES.size()) {
destoryLast();
}
CACHE_SIZE = size;
}
/**
* 加入一个图片处理请求到图片创建队列
*
* @param path
* 图片路径(本地)
* @param width
* 图片宽度
* @param height
* 图片高度
*/
public static void addTask(String path, int width, int height) {
QueueEntry entry = new QueueEntry();
entry.path = path;
entry.width = width;
entry.height = height;
synchronized (TASK_QUEUE) {
String key = createKey(path, width, height);
if (!TASK_QUEUE_INDEX.contains(key)
&& !IMG_CACHE_INDEX.containsKey(key)) {
TASK_QUEUE.add(entry);
TASK_QUEUE_INDEX.add(key);
TASK_QUEUE.notify();
}
}
}
/**
* 通过图片路径返回图片实际大小
* @param path 图片物理路径
* @return
*/
public static Size getBitMapSize(String path) {
File file = new File(path);
if (file.exists()) {
InputStream in = null;
try {
in = new FileInputStream(file);
BitmapFactory.decodeStream(in, null, OPTIONS_GET_SIZE);
return new Size(OPTIONS_GET_SIZE.outWidth,
OPTIONS_GET_SIZE.outHeight);
} catch (FileNotFoundException e) {
return ZERO_SIZE;
} finally {
closeInputStream(in);
}
}
return ZERO_SIZE;
}
// ------------------------------------------------------------------ private Methods
// 将图片加入队列头
private static Bitmap useBitmap(String path, int width, int height) {
Bitmap bitMap = null;
String key = createKey(path, width, height);
synchronized (LOCKED) {
bitMap = IMG_CACHE_INDEX.get(key);
if (null != bitMap) {
if (CACHE_ENTRIES.remove(key)) {
CACHE_ENTRIES.addFirst(key);
}
}
}
return bitMap;
}
// 回收最后一张图片
private static void destoryLast() {
synchronized (LOCKED) {
String key = CACHE_ENTRIES.removeLast();
if (key.length() > 0) {
Bitmap bitMap = IMG_CACHE_INDEX.remove(key);
if (bitMap != null && !bitMap.isRecycled()) {
bitMap.recycle();
bitMap = null;
}
}
}
}
// 创建键
private static String createKey(String path, int width, int height) {
if (null == path || path.length() == 0) {
return "";
}
return path + "_" + width + "_" + height;
}
// 通过图片路径,宽度高度创建一个Bitmap对象
private static Bitmap createBitmap(String path, int width, int height) {
File file = new File(path);
if (file.exists()) {
InputStream in = null;
try {
in = new FileInputStream(file);
Size size = getBitMapSize(path);
if (size.equals(ZERO_SIZE)) {
return null;
}
int scale = 1;
int a = size.getWidth() / width;
int b = size.getHeight() / height;
scale = Math.max(a, b);
synchronized (OPTIONS_DECODE) {
OPTIONS_DECODE.inSampleSize = scale;
Bitmap bitMap = BitmapFactory.decodeStream(in, null,
OPTIONS_DECODE);
return bitMap;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
closeInputStream(in);
}
}
return null;
}
// 关闭输入流
private static void closeInputStream(InputStream in) {
if (null != in) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
// 图片大小
static class Size {
private int width, height;
Size(int width, int height) {
this.width = width;
this.height = height;
}
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
}
// 队列缓存参数对象
static class QueueEntry {
public String path;
public int width;
public int height;
}
}
测试代码使用android1.6完成,需要的可移步下载,地址为:http://download.csdn.net/detail/liaoxingliao/3756187 (这个工程内部的这个工具类由于我的疏忽有几个地方写错了,现在但是那个资源上传完以后,既不能修改,又不能删除.有谁知道怎么改的,希望告诉我一下)
四,
尽量不要使用setImageBitmap或setImageResource或BitmapFactory.decodeResource来设置一张大图,
因为这些函数在完成decode后,最终都是通过java层的createBitmap来完成的,需要消耗更多内存。
因此,改用先通过BitmapFactory.decodeStream方法,创建出一个bitmap,再将其设为ImageView的 source,
decodeStream最大的秘密在于其直接调用JNI>>nativeDecodeAsset()来完成decode,
无需再使用java层的createBitmap,从而节省了java层的空间。
如果在读取时加上图片的Config参数,可以跟有效减少加载的内存,从而跟有效阻止抛out of Memory异常
另外,decodeStream直接拿的图片来读取字节码了, 不会根据机器的各种分辨率来自动适应,
使用了decodeStream之后,需要在hdpi和mdpi,ldpi中配置相应的图片资源,
否则在不同分辨率机器上都是同样大小(像素点数量),显示出来的大小就不对了。
另外,以下方式也大有帮助:
1. InputStream is = this.getResources().openRawResource(R.drawable.pic1);
BitmapFactory.Options options=new BitmapFactory.Options();
options.inJustDecodeBounds = false;
options.inSampleSize = 10; //width,hight设为原来的十分一
Bitmap btp =BitmapFactory.decodeStream(is,null,options);
2. if(!bmp.isRecycle() ){
bmp.recycle() //回收图片所占的内存
system.gc() //提醒系统及时回收
}
以下奉上一个方法:
Java代码
1. /**
2. * 以最省内存的方式读取本地资源的图片
3. * @param context
4. * @param resId
5. * @return
6. */
7. public static Bitmap readBitMap(Context context, int resId){
8. BitmapFactory.Options opt = new BitmapFactory.Options();
9. opt.inPreferredConfig = Bitmap.Config.RGB_565;
10. opt.inPurgeable = true;
11. opt.inInputShareable = true;
12. //获取资源图片
13. InputStream is = context.getResources().openRawResource(resId);
14. return BitmapFactory.decodeStream(is,null,opt);
15. }
================================================================================
Android内存溢出的解决办法
转自:http://www.cppblog.com/iuranus/archive/2010/11/15/124394.html?opt=admin
昨天在模拟器上给gallery放入图片的时候,出现java.lang.OutOfMemoryError: bitmap size exceeds VM budget 异常,图像大小超过了RAM内存。
模拟器RAM比较小,只有8M内存,当我放入的大量的图片(每个100多K左右),就出现上面的原因。
由于每张图片先前是压缩的情况,放入到Bitmap的时候,大小会变大,导致超出RAM内存,具体解决办法如下:
//解决加载图片 内存溢出的问题
//Options 只保存图片尺寸大小,不保存图片到内存
BitmapFactory.Options opts = new BitmapFactory.Options();
//缩放的比例,缩放是很难按准备的比例进行缩放的,其值表明缩放的倍数,SDK中建议其值是2的指数值,值越大会导致图片不清晰
opts.inSampleSize = 4;
Bitmap bmp = null;
bmp = BitmapFactory.decodeResource(getResources(), mImageIds[position],opts);
...
//回收
bmp.recycle();
通过上面的方式解决了,但是这并不是最完美的解决方式。
通过一些了解,得知如下:
优化Dalvik虚拟机的堆内存分配
对 于Android平台来说,其托管层使用的Dalvik Java VM从目前的表现来看还有很多地方可以优化处理,比如我们在开发一些大型游戏或耗资源的应用中可能考虑手动干涉GC处理,使用 dalvik.system.VMRuntime类提供的setTargetHeapUtilization方法可以增强程序堆内存的处理效率。当然具体 原理我们可以参考开源工程,这里我们仅说下使用方法: private final static float TARGET_HEAP_UTILIZATION = 0.75f; 在程序onCreate时就可以调用
VMRuntime.getRuntime().setTargetHeapUtilization(TARGET_HEAP_UTILIZATION); 即可。
Android堆内存也可自己定义大小
对于一些Android项目,影响性能瓶颈的主要是Android自己内存管理机制问题,目前手机厂商对RAM都比较吝啬,对于软件的流畅性来说RAM对 性能的影响十分敏感,除了 优化Dalvik虚拟机的堆内存分配外,我们还可以强制定义自己软件的对内存大小,我们使用Dalvik提供的 dalvik.system.VMRuntime类来设置最小堆内存为例:
private final static int CWJ_HEAP_SIZE = 6* 1024* 1024 ;
VMRuntime.getRuntime().setMinimumHeapSize(CWJ_HEAP_SIZE); //设置最小heap内存为6MB大小。当然对于内存吃紧来说还可以通过手动干涉GC去处理
bitmap 设置图片尺寸,避免 内存溢出 OutOfMemoryError的优化方法
★android 中用bitmap 时很容易内存溢出,报如下错误:Java.lang.OutOfMemoryError : bitmap size exceeds VM budget
● 主要是加上这段:
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 2;
● eg1:(通过Uri取图片)
private ImageView preview;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 2;//图片宽高都为原来的二分之一,即图片为原来的四分之一
Bitmap bitmap = BitmapFactory.decodeStream(cr
.openInputStream(uri), null, options);
preview.setImageBitmap(bitmap);
以上代码可以优化内存溢出,但它只是改变图片大小,并不能彻底解决内存溢出。
● eg2:(通过路径去图片)
private ImageView preview;
private String fileName= "/sdcard/DCIM/Camera/2010-05-14 16.01.44.jpg";
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 2;//图片宽高都为原来的二分之一,即图片为原来的四分之一
Bitmap b = BitmapFactory.decodeFile(fileName, options);
preview.setImageBitmap(b);
filePath.setText(fileName);
★Android 还有一些性能优化的方法:
● 首先内存方面,可以参考 Android堆内存也可自己定义大小 和 优化Dalvik虚拟机的堆内存分配
● 基础类型上,因为Java没有实际的指针,在敏感运算方面还是要借助NDK来完成。Android123提示游戏开发者,这点比较有意思的是Google 推出NDK可能是帮助游戏开发人员,比如OpenGL ES的支持有明显的改观,本地代码操作图形界面是很必要的。
● 图形对象优化,这里要说的是Android上的Bitmap对象销毁,可以借助recycle()方法显示让GC回收一个Bitmap对象,通常对一个不用的Bitmap可以使用下面的方式,如
if(bitmapObject.isRecycled()==false) //如果没有回收
bitmapObject.recycle();
● 目前系统对动画支持比较弱智对于常规应用的补间过渡效果可以,但是对于游戏而言一般的美工可能习惯了GIF方式的统一处理,目前Android系统仅能预览GIF的第一帧,可以借助J2ME中通过线程和自己写解析器的方式来读取GIF89格式的资源。
● 对于大多数Android手机没有过多的物理按键可能我们需要想象下了做好手势识别 GestureDetector 和重力感应来实现操控。通常我们还要考虑误操作问题的降噪处理。
Android堆内存也可自己定义大小
对于一些大型Android项目或游戏来说在算法处理上没有问题外,影响性能瓶颈的主要是Android自己内存管理机制问题,目前手机厂商对RAM都比 较吝啬,对于软件的流畅性来说RAM对性能的影响十分敏感,除了上次Android开发网提到的 优化Dalvik虚拟机的堆内存分配外,我们还可以强制定义自己软件的对内存大小,我们使用Dalvik提供的 dalvik.system.VMRuntime类来设置最小堆内存为例:
private final static int CWJ_HEAP_SIZE = 6* 1024* 1024 ;
VMRuntime.getRuntime().setMinimumHeapSize(CWJ_HEAP_SIZE); //设置最小heap内存为6MB大小。当然对于内存吃紧来说还可以通过手动干涉GC去处理,我们将在下次提到具体应用。
优化Dalvik虚拟机的堆内存分配
对 于Android平台来说,其托管层使用的Dalvik JavaVM从目前的表现来看还有很多地方可以优化处理,比如我们在开发一些大型游戏或耗资源的应用中可能考虑手动干涉GC处理,使用 dalvik.system.VMRuntime类提供的setTargetHeapUtilization方法可以增强程序堆内存的处理效率。当然具体 原理我们可以参考开源工程,这里我们仅说下使用方法: private final static floatTARGET_HEAP_UTILIZATION = 0.75f; 在程序onCreate时就可以调用
VMRuntime.getRuntime().setTargetHeapUtilization(TARGET_HEAP_UTILIZATION); 即可。
介绍一下图片占用进程的内存算法吧。
android中处理图片的基础类是Bitmap,顾名思义,就是位图。占用内存的算法如下:
图片的width*height*Config。
如果Config设置为ARGB_8888,那么上面的Config就是4。一张480*320的图片占用的内存就是480*320*4 byte。
前面有人说了一下8M的概念,其实是在默认情况下android进程的内存占用量为16M,因为Bitmap他除了java中持有数据外,底层C++的 skia图形库还会持有一个SKBitmap对象,因此一般图片占用内存推荐大小应该不超过8M。这个可以调整,编译源代码时可以设置参数。
相关文章推荐
- 关于解决android图片设置时outofmemery的问题!!!!!!!!!!
- 关于 android 加载 res 图片 out of memory 问题 解决 同样适用于 sd卡图片
- 完美解决 android 网络下载图片 outofmemery 问题!
- 解决Android加载大图片内存溢出的问题(OutofMemoryException)
- Android解决GridView异步加载大量图片时出现Out Of Memory问题00M
- Android完美解决GridView异步加载图片和加载大量图片时出现Out Of Memory问题
- Android中解决加载过多图片出现的OutOfMemoryOutOfMemory问题 .
- 解决Android加载大图片内存溢出的问题(OutofMemoryException)
- android viewpager outofmemery问题解决
- Android完美解决GridView异步加载图片和加载大量图片时出现Out Of Memory问题
- android开发步步为营之50:android关于加载大图片java.lang.OutOfMemoryError错误的解决
- Android有效解决加载大图片时内存溢出的问题 Out of memory
- android应用程序,图片OutOfMemory问题解决方案
- Android完美解决GridView异步加载图片和加载大量图片时出现Out Of Memory问题
- 【android】解决因为图片太大引起的内存不足问题,Caused by: java.lang.OutOfMemoryError: bitmap size exceeds VM budget
- 关于android编程遇到java.lang.OutOfMemoryError: bitmap size exceeds VM budget此类问题的原因及解决办法
- Android ImageSwitcher 和 Gallery 浏览图片时 OutofMemory问题的解决
- Android中图片过大造成内存溢出,OOM(OutOfMemory)异常解决方法
- 【转】解决Android因加载多个大图引起的OutOfMemoryError,内存溢出的问题
- JVM内存的设置(解决eclipse下out of memory问题)