zl程序教程

您现在的位置是:首页 >  移动开发

当前栏目

修改android最小堆内存详解手机开发

Android内存手机开发 详解 修改 最小
2023-06-13 09:20:13 时间
[java]
view plain
copy int CWJ_HEAP_SIZE = 10 * 1024 * 1024; //10M的内存  VMRuntime.getRuntime().setMinimumHeapSize(CWJ_HEAP_SIZE); 

深层理解,进入andorid源码内部:

当应用程序分配内存时,会调用到dalvik/vm/alloc/HeapSource.c中的 dvmTrackExternalAllocation()方法,继而调用到externalAllocPossible()方法,该方法要求当前堆已使 用的大小(由currentHeapSize和hs- externalBytesAllocated构成)加上我们需要再次分配的内存大小不能超 过堆的最大内存值,如果超过就会报错。
有两个地方决定了一个堆的最大内存: 
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:


[plain]
view plain
copy 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; 
[plain]
view plain
copy 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);