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 current version is out of date. I have been sticking it in the oncreate of my first activity, pretty sure there has to be a better place to put this. Any recommendations of somewhere I can put it where it will get called once on startup?
Share
You can write a custom Application class (extend from android.app.Application). Override
onCreateto specify what happens when the application is started:You’ll then need to register your custom class in the manifest file:
Edit:
In response to David Cesarino, I disagree with the purpose of the
Applicationclass. If you rely on theActivity‘sonCreate, then what’s to stop it from becoming the same huge class of miscellaneous purposes… if you need something to happen when the application starts, you have to write that code somewhere; and theActivitywould probably become more cluttered because you have to performActivityspecific logic in it as well. If you’re worried about clutter, then separate the logic into other classes and call them from theApplication. Using theSharedPreferencesto determine whether or not the logic should execute seems like more of a work-around to a problem that’s already been solved.Dianne Hackborn seems to be referring to data, not logic, in which I totally agree. Static variables are much better than Application level variables… better scoping and type safety make maintainability/readability much easier.