Reputation:
I've got a question that is annoying me.
With Android, I've got an application that seems to be calling onCreate
every time a new instance of an activity is created, because this activity is the son of an another and it finishes itself while it ends its role for one piece of data.
The calling of onCreate
every time seems to be re-parsing the XML to create the views and re-attaching/re-creating the listeners to the code and so on. So Is there a way to cache an activity to be recalled every time, without seeing it if we click on the back button in the mobile device? It's like having it really hidden (not accessible with the back button) and destroyed only if it's necessary.
Thanks everyone in advance :)
Upvotes: 6
Views: 9091
Reputation: 596773
You can not prevent onCreate from being called at every Activity creation because that is the way things work.
Your problem here is more an architecture problem : you have a feature that you use very often but you dedicate a whole heavy activity to it.
If you are looking for speed and responsiveness, an answser can be the ViewFlipper. You define an unique Activity, and when you use your feature, you just change the view. You entire app is loaded at the very start, then it stays in memory until Dalvik needs some. You can find a pretty complex example in the code of the open source app astrid.
Upvotes: 0
Reputation: 14646
Android will handle most applicable View and activity caching and you shouldn't have to worry about it. I -strongly- warn against alexkipar's approach. This is quite naive and will only worsen performance as well as create memory leaks and flat out wrong behavior.
If you feel Activity's are being created too often, I would recommend making sure you are using and understanding the Activity lifecycle correctly. As with every system, Android balances between efficiency and reusability, and there are always tradeoffs to make.
A common misconception you mentioned involves parsing XML. XML for views is not stored as pure XML, but rather in a compiled form for efficiency. You do not have to worry about this, trust that the system is trying to make things as efficient as it can for you.
Upvotes: 6
Reputation: 78003
If it gets called it means your process finished executing or was killed by the system.
onCreate
will get called each time your activity starts. That's just the way the Activity lifecycle works and there's not much you can do there.
If you wish that your process remain in memory then you should consider implementing it as a Service.
Upvotes: 1