How to run particular code only once at every Android App Start?

Please note that this tutorial explains to run some piece of code only once at EVERY App start. Don’t confuse it with “How to run some piece of code only once per lifecycle?”. Most of the android developers are aware that there’s no proper method in android which is executed only once when the app starts. For example, onCreate() and onStart() methods are executed every time activity is created and it is done every time user changes screen orientation or navigate back and forth between activities. 
So if you put some code in any of two methods, it will be executed every time, for example, if the user changes device orientation or get back to the activity using the back button. This is clearly not what we wanted! We need to execute some code only at the start of the application and not after that until the application is terminated.
There’s a very easy method to achieve this. Just follow these steps:
1. Open your existing project. Add a class named “Startup”.
2. Once added, replace its code with following: (Don’t forget to retain your package name at the top)

public class Startup extends Application {
public void onCreate(){
// Place your code here which will be executed only once

3. Now the final thing is to add this class to manifest file. In tag, put the following:


4. The final manifest file should look like this:

Hope this solves your problem. Let us know 🙂

Related posts