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
You can write a custom Application class (extend from android.app.Application). Override onCreate
to specify what happens when the application is started:
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
// Do something here.
}
}
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 Application
class. If you rely on the Activity
's onCreate
, 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 the Activity
would probably become more cluttered because you have to perform Activity
specific logic in it as well. If you're worried about clutter, then separate the logic into other classes and call them from the Application
. Using the SharedPreferences
to 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.