Search code examples
androidandroid-intentandroid-activityandroid-manifestback-stack

How to run an activity only once like Splash screen


In my app, I would like to run the Splash screen once at first run only but the problem is that I already placed in the Manifest this line: android:noHistory="true" which works great if I press back button and exits the app but note that the app is still in the background running, and when I press the app icon it goes back again to the Splash screen then my Registration page. I wanted to be redirected to the Registration page directly when I reopen my application.

How do I do this? Thanks ahead for any suggestions.


Solution

  • So here's what I did, in my SplashActivity(onCreate):

        SharedPreferences settings = getSharedPreferences("prefs", 0);
        SharedPreferences.Editor editor = settings.edit();
        editor.putBoolean("firstRun", true);
        editor.commit();
    
        Intent intent = new Intent(this, RegistrationActivity.class);
        startActivity(intent);
    

    SplashActivity(onResume):

    @Override
    public void onResume() {
        super.onResume();
        SharedPreferences settings = getSharedPreferences("prefs", 0);
        boolean firstRun = settings.getBoolean("firstRun", true);
        if (!firstRun) {
            Intent intent = new Intent(this, RegistrationActivity.class);
                startActivity(intent);
            Log.d("TAG1", "firstRun(false): " + Boolean.valueOf(firstRun).toString());
        } else {
            Log.d("TAG1", "firstRun(true): " + Boolean.valueOf(firstRun).toString());
        }
    }
    

    In my RegistrationActivity(onCreate):

        SharedPreferences settings = getSharedPreferences("prefs", 0);
        SharedPreferences.Editor editor = settings.edit();
        editor.putBoolean("firstRun", false);
        editor.commit();
    
        boolean firstRun = settings.getBoolean("firstRun", true);
        Log.d("TAG1", "firstRun: " + Boolean.valueOf(firstRun).toString());
    

    And then disabled back button to prevent going back unless the user presses Home:

    @Override
    public void onBackPressed() {
    }
    

    Big thanks for those that contributed!