Loading...

android-platform@googlegroups.com

[Prev] Thread [Next]  |  [Prev] Date [Next]

Dalvik heap fragmentation and recovery Mattaku Betsujin Mon Mar 09 11:01:41 2009

Hello,

I have a web viewer app that needs to create Strings that are longer than
200K characters (to pass to WebView). I also maintain a Hashtable of Strings
to act as a cache of the downloaded HTML pages.

After a while, in some rare cases, the Dalvik heap is so fragmented that it
can no longer allocate a contiguous chunk for large Strings.

I am looking for a good way to recover from this gracefully. I have only two
ideas:

Solution 1:

in onStop() function, check if Runtime.totalMemory() is larger than 12MB
(this is pretty rare, but could happen). If so, quit the activity by calling
android.os.Process.killProcess(android.os.Process.myPid()).

However, if the user keeps using my app and doesn't bring up other
activities, onStop() is never called.

Solution 2:

Include a "restart helper" activity in the app. When the main activity's
heap is over 12MB, start the Restart Helper with FLAG_ACTIVITY_NEW_TASK.
Restart Helper would display a "cleaning up ..." screen, kill the main
activity's process, and relaunch it with FLAG_ACTIVITY_NEW_TASK. Finally,
kill the Restart Helper process.

Is there anything wrong with Solution 2? Is it safe to kill processes this
way? If I call SharedPreferences.Editor.commit() before calling killProcess,
is the content of the SharedPreferences guaranteed to be properly saved to
disk?

Also, is there a better solution? I probably shalt not kill.

Thanks!