A common Android development challenge: executing code exclusively during an application’s initial launch. A practical use case is displaying a tutorial or onboarding flow only when users first open the app.

The Solution

Leverage SharedPreferences to track whether the app has been launched before:

public class MainActivity extends Activity {

    private static final String PREFS_NAME = "MyPrefs";
    private static final String FIRST_LAUNCH_KEY = "firstLaunch";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (isFirstLaunch()) {
            // Your first-launch code here
            showTutorial();
            markFirstLaunchComplete();
        }
    }

    private boolean isFirstLaunch() {
        SharedPreferences prefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
        return prefs.getBoolean(FIRST_LAUNCH_KEY, true);
    }

    private void markFirstLaunchComplete() {
        SharedPreferences prefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
        prefs.edit()
             .putBoolean(FIRST_LAUNCH_KEY, false)
             .apply();
    }

    private void showTutorial() {
        // Display your onboarding UI
    }
}

How It Works

  1. Check the SharedPreferences for a boolean flag
  2. If the flag doesn’t exist (or is true), it’s the first launch
  3. Run your initialization code
  4. Set the flag to false to prevent future execution

Important Caveat

This approach resets when the app is uninstalled, since SharedPreferences data is cleared with the app. If you need persistence across installs, consider:

  • Storing the flag on a server
  • Using device identifiers (with appropriate privacy considerations)
  • Using Android’s Backup API

For most use cases like tutorials and onboarding, resetting on reinstall is actually the desired behavior.