KaliMa KaliMa - 1 month ago 9
Android Question

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?

Answer

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();
    }
}
Comments