Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Repeated activity initializations and memory usage

Thanks for reading by question, albeit a really noob-ish one...

How does the Android system manage memory with regards to activity initialization, specifically if an activity is initialized through other activities? This has been a lingering question in my mind for a while, but I'll try to illustrate with an example:

Say I have 3 activities - A, B and C - with activity A being the one that is launched when the application is started for the very first time. Now, let's say activity A has buttons to navigate to activities B and C, and those activities are launched using Android's startActivity() function, passing it an Intent instance. Similarly, let's say activities B and C have buttons to launch their counterpart activities...make sense so far?

Now, if I then use the startActivity() to:

  • start activity B from activity A
  • then start activity C from activity B
  • then start activity A from activity C
  • then repeat the above steps indefinitely (so going around in circles)

...would it be fair to assume that the Android system would "know" that the activities had already been started previously and wouldn't re-initialize them and kill more and more memory, but rather call something like the onRestart() functionality to rather "switch" back to an already initialized instance of the activity?

Quite an explanation for a really simple question / problem...apologies if this has already been asked and answered somewhere else...I couldn't find a clear answer anywhere else, even while reading through the Android training section on the Android developers site.

like image 231
Chris Kempen Avatar asked Sep 07 '12 15:09

Chris Kempen


1 Answers

The answer is: It depends. :-)

If you use the standard settings for the activities A, B and C, your application will run out of memory. The reason is that Android will keep each activity in the "Back Stack" that allows the user to navigate back by pushing the back button.

However, if you set the android:launchMode of your activities to singleTop in the AndroidManifest.xml file then Android will route the intents to the running instances of the activities by invoking onNewIntent() in the activity.

You can read more about it in the Android Developer Documentation regarding launch modes.

like image 187
Nicholas Avatar answered Nov 09 '22 08:11

Nicholas