KaliMa
KaliMa

Reputation: 2060

Run certain operations only when the app is first installed

Let us presume that we have a function defined this way:

public class MyClass {
    public static void RunFirstTime() {
        //...
    }
}

The very first time I install the app, I want to run RunFirstTime() but then any other time I run the app, that function should not run.

Is there a built-in way to do this?

Upvotes: 0

Views: 42

Answers (2)

zon7
zon7

Reputation: 539

Just use SharedPreferences and store a boolean variable when you are done with first run.

To be more clear, the code should be something like this:

public static void RunFirstTime() {
    SharedPreferences prefs = getPreferences(MODE_PRIVATE);
    boolean firstRun = sPref.getBoolean("firstRun", true);
    if(firstRun){
        //Do something here
        ....
        //Save firstRun = false in order to not repeat next time 
        Editor prefEdit = sPref.edit();
        prefEdit.putBoolean("firstRun", false);
        prefEdit.commit();
    }
}

Upvotes: 4

Andrii Omelchenko
Andrii Omelchenko

Reputation: 13353

Try code like this:

public boolean isFirstRun() {
    SharedPreferences sPref;
    sPref = getPreferences(MODE_PRIVATE);
    boolean isFirstRun = sPref.getBoolean("FirstRun", true);
    Editor ed = sPref.edit();
    ed.putBoolean("FirstRun", false);
    ed.commit();
    return isFirstRun;
  }

Upvotes: 0

Related Questions