Run code only once after an application is installed on Android device

  1. Check if boolean X is True in shared preferences
  2. If not:
    a. Run the special code
    b. Save x as true in shared preferences

For example:

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if(!prefs.getBoolean("firstTime", false)) {
    // run your one time code
    SharedPreferences.Editor editor = prefs.edit();
    editor.putBoolean("firstTime", true);
    editor.commit();
}

I've used a shared preference in the past, but if you are wanting to do something onInstall you could also look at a install receiver. MyInstallReciever implements BroadcastReciever

<receiver
    android:name="com.MyInstallReciever"
    android:exported="true">
    <intent-filter>
        <action
            android:name="com.android.vending.INSTALL_REFERRER" />
    </intent-filter>
</receiver>

Tags:

Android