How to launch activity only once when app is opened for first time?

What I've generally done is add a check for a specific shared preference in the Main Activity : if that shared preference is missing then launch the single-run Activity, otherwise continue with the main activity . When you launch the single run Activity create the shared preference so it gets skipped next time.

EDIT : In my onResume for the default Activity I do this:

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
    boolean previouslyStarted = prefs.getBoolean(getString(R.string.pref_previously_started), false);
    if(!previouslyStarted) {
        SharedPreferences.Editor edit = prefs.edit();
        edit.putBoolean(getString(R.string.pref_previously_started), Boolean.TRUE);
        edit.commit();
        showHelp();
    }

Basically I load the default shared preferences and look for the previously_started boolean preference. If it hasn't been set I set it and then launch the help file. I use this to automatically show the help the first time the app is installed.


SharedPreferences dataSave = getSharedPreferences("firstLog", 0);

if(dataSave.getString("firstTime", "").toString().equals("no")){ // first run is happened
}
else{ //  this is the first run of application
SharedPreferences.Editor editor = dataSave.edit();
                editor.putString("firstTime", "no");
                editor.commit();
}

Post the following code within your onCreate statement

   Boolean isFirstRun = getSharedPreferences("PREFERENCE", MODE_PRIVATE)
            .getBoolean("isFirstRun", true);

    if (isFirstRun) {
        //show start activity

        startActivity(new Intent(MainActivity.this, FirstLaunch.class));
        Toast.makeText(MainActivity.this, "First Run", Toast.LENGTH_LONG)
                .show();
    }


       getSharedPreferences("PREFERENCE", MODE_PRIVATE).edit()
                .putBoolean("isFirstRun", false).commit();

Replace FirstLaunch.class with the class that you would like to launch


something like this might work.

public class MyPreferences {

    private static final String MY_PREFERENCES = "my_preferences";  

    public static boolean isFirst(Context context){
        final SharedPreferences reader = context.getSharedPreferences(MY_PREFERENCES, Context.MODE_PRIVATE); 
        final boolean first = reader.getBoolean("is_first", true);
        if(first){
            final SharedPreferences.Editor editor = reader.edit();
            editor.putBoolean("is_first", false);
            editor.commit();
        }
        return first;
    }

}

usage

boolean isFirstTime = MyPreferences.isFirst(CurrentActivity.this);
if (isFirstTime) {
    NewActivity.show(CurrentActivity.this);
}

...

public class NewActivity extends Activity {
    public static void show(Context context) {
        final Intent intent = new Intent(context, NewActivity.class);
        context.startActivity(intent);
    }
}

Tags:

Android