I am writing a procedure to sync large number of contacts with the Android Contacts database. The downloading works fine for about 700 contacts after which i am consistantly getting a memory heap error which calls infinite number of GC statement and ends up Re-booting the Phone. I am facing the problem on HTC desire.
I checked heap size of the application using the Heap alocation tool from DDMS as well as extracted the hprof file using Debug.dumpHprofData. Both the logs indicated that the Heap size is about 2.4MB.
However i get the following logs which indicates that the heap size is more that 32.MB
dalvikvm-heap(92): Clamp target GC heap from 33.999MB to 32.000MB
dalvikvm(92): GC_FOR_MALLOC freed 2 objects / 48 bytes in 313ms
I had inserted following log statements in loop where my contatcs downloading logic was written.
Log.e("Memory", "free mem =" +runtime.freeMemory());
Log.e("Memory", "total memory =" +runtime.totalMemory());
These are the initial and final values of the statement printed
---------------------------------------------------------------
11-11 12:56:04.168: ERROR/Memory(25132): free mem =871248
11-11 12:56:04.168: ERROR/Memory(25132): total memory =4202464
---------------------------------------------------------------
11-11 13:01:55.408: ERROR/Memory(25132): free mem =891640
11开发者_Go百科-11 13:01:55.408: ERROR/Memory(25132): total memory =4726752
---------------------------------------------------------------
This indicates that apperently there are no memory leaks present in the syncing contacts logic.
Can someone please let me know for why is the heap size increased (upto 32.00Mb) to such a extent that the device re-boots itself? I am new to Android and Java so please go easy on me :).....
While this isn't the best answer I'd highly recommend you watch the video of the Memory management for Android Apps talk at Google IO 2011. It does a great job explaining how to manage memory and what the messages you are seeing actually mean.
You need to post your code for anyone to help. Otherwise i assume two things:
By downloading you mean fetching data from a remote location? It seems like you're keeping a lot of references to your data in memory. Do you have to? Depending on what you're trying to achieve, there's typically a few things you could try to minimize your memory footprint. To start with, I'd make sure I don't use any String references but I'd stream the data directly to the consumer. Also, try to process all your data in chunks. Do you also need to persist the data to the file system? If so, stream directly to the file system and avoid memory storage all together. If you post some code, that might help.
精彩评论