Android newbee here, I have some code that I want to run when my android app first starts up. It checks the version of the local database and downloads a new version if the curr
First, look at the Activity lifecycle.
Answering your question, you could put code in any of those "start-up" methods, depending on what you want to do and, mostly important, when you want to trigger that. For what you asked, onCreate
is the reasonable place.
I have been sticking it in the oncreate of my first activity, pretty sure there has to be a better place to put this.
And why is that? Any code has an entry point, right? In Android Activities it just happens to be onCreate
(again, see above link for the full details). Besides event handling, which are responses to events happening outside the main sequence of calls, you put stuff in onCreate
.
If you're concerned about the method becoming huge, then that's another problem. Abstract your code better, I say. For checking preliminary stuff, people generally provide a "Loading" activity, before starting the main activity of the app.
edited:
This is a follow up to what drumboog proposed, since my comment started to grow in complexity to be "just a comment".
Personally, I'd avoid extending the Application
class for the sole reason of executing code early on, more so a code that is not that sensible in priority (versioning databases). The Application
class is mostly used as an easy way to persist state between Activity
'ies, not as a way to "do everything". In short, I feel the Application
class is commonly abused.
For what you want, you could perfectly achieve that calling code in Activity
onCreate
. That reduces complexity, because I've seen people stuffing Application
until it becomes a huge class of miscellaneous code purposes. And that's a no-no for maintenance, with logic problems of its own.
Besides, if you truly want another solution, completely disassociated with the UI, you should think about implementing a Service
instead (but I don't think it's necessary for just that).
Both of those concerns were previously addressed by Dianne Hackborn (or what I got from her message).