开发者

Android: removing/destroying objects when screen is rotated

I am finding that performance degrades after one or more screen rotations, and I presume that this is likely to be because an App's main Activity is destroyed and recreated each time the screen is rotated and that my app must be leaking memory when that happens.

I have read that, contrary to what one might expect, not all the objects created by an app's main Activity (or in classes called by that Activity) are destroyed when the activity is destroyed. Specifically, I think I have read (although I can't now find where) that if the View uses a large bitmap member object then the Activity's onDestroy() method should be over-ridden and the bitmap should be explicitly recycled.

Are there other objects that need to be destroyed or removed when the Activity is destroyed? What about Listeners? Is there a comprehensiv开发者_开发问答e tutorial or guide on this subject?


Is there a comprehensive tutorial or guide on this subject?

Not really.

Are there other objects that need to be destroyed or removed when the Activity is destroyed? What about Listeners?

Bitmaps are unusual, in part because they use memory outside of the 16MB heap, if I understand the byzantine Android memory model correctly.

Beyond large bitmaps, the biggest thing you really need to worry about are things that prevent normal garbage collection from working. Anything that holds onto the activity, directly or indirectly, from a static context will keep the activity from being garbage collected. Examples include:

  • static data members on classes (e.g., you rig up your own listener framework with one of your services, so your service holds onto a listener which holds onto your activity)
  • threads (e.g., you manually fork a background thread and do not terminate it)


Note that putting android:configChanges="orientation" in the Manifest prevents the Activity from being destroyed when the screen is rotated. So I no longer need to worry about whether I need to destroy or remove individual bitmaps or other objects! (Thanks to Ribo for pointing this out on another thread.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜