在oncreate的时候加入如下代码段即可保证该运行程序有足够的内存了:
- int CWJ_HEAP_SIZE = 10 * 1024 * 1024; //10M的内存
- VMRuntime.getRuntime().setMinimumHeapSize(CWJ_HEAP_SIZE);
别忘了导入包:
- import dalvik.system.VMRuntime;
深层理解,进入andorid源码内部:
有两个地方决定了一个堆的最大内存:
1)dalvik/vm/Init.c中的
gDvm.heapSizeMax = 16 * 1024 * 1024; // Spec says 75% physical mem
2)frameworks/base/core/jni/AndroidRuntime.cpp中的
property_get("dalvik.vm.heapsize", heapsizeOptsBuf+4, "16m");
因此解决办法就是将默认的16M改大一点。
解决办法:
1. 修改dalvik/vm/Init.c:
- static void setCommandLineDefaults()
- * TODO: base these on a system or application-specific default
- */
- gDvm.heapSizeStart = 2 * 1024 * 1024; // Spec says 16MB; too big for us.
- - gDvm.heapSizeMax = 16 * 1024 * 1024; // Spec says 75% physical mem
- + gDvm.heapSizeMax = 32 * 1024 * 1024; // Spec says 75% physical mem
- gDvm.stackSize = kDefaultStackSize;
2. 修改frameworks/base/core/jni/AndroidRuntime.cpp:
- int AndroidRuntime::startVm(JavaVM** pJavaVM, JNIEnv** pEnv)
- //options[curOpt++].optionString = "-verbose:class";
- strcpy(heapsizeOptsBuf, "-Xmx");
- - property_get("dalvik.vm.heapsize", heapsizeOptsBuf+4, "16m");
- + property_get("dalvik.vm.heapsize", heapsizeOptsBuf+4, "32m");
- //LOGI("Heap size: %s", heapsizeOptsBuf);
- opt.optionString = heapsizeOptsBuf;
- mOptions.add(opt);
-