android memory management in activity lifecycle

前端 未结 5 1533
小鲜肉
小鲜肉 2020-12-25 13:47

My question is a little bit complicated.

I want to understand how the app treats resources (especially images for backgrounds, buttons, etc.) when Activity is starte

5条回答
  •  隐瞒了意图╮
    2020-12-25 14:15

    Okay so we have the following situation:

    A > onCreate
    A > onStart
    A > onResume
    A > Use up a load of memory (A could even use up too much and crash)
    A > Launch activity B
    B > onCreate
    A > onPause
    B > onStart
    A > onStop
    B > onResume
    B > Use up a load of memory 
    

    If B uses up enough memory then the Android system will kill activity A (you'll notice the onPause and onStop methods of A have already been called so it's already been given a chance to save it's state)

    If you then press the back button the Android system will just start activity A again (and if it's clever it should remember it's last state) so it looks like nothing ever happened to the user.

    So to be a bit clearer: if you start B and then finish A, B will essentially just replace A in the activity stack and pressing the Back button in activity B will just exit your and app and not return to activity A.

    If on the other hand you start B without finishing A, then pressing the back button in B will take you back to A. While activity A is in the background it could be killed to reclaim memory, but Android will recreate it as needed when the user navigates through the activities stack.

    Also if you have in memory-caches of multiple objects (e.g. bitmaps/drawables) then back your collection by SoftReferences so that the GC can clear them up if it's running low on memory.

提交回复
热议问题