Search code examples
javaandroidxmlandroid-activitylaunch

Run activity only once, then always run the main one


As the title says, Scenario is: On first time using the app, Show Screen A. Once you are done with screen A, the button will lead to you Screen B. From now on and forever, the Screen B will always be main "Screen"(Activity?) when you start the app. I am trying this 2 days and i can't get it. Somebody please explain a little detailed, or even better throw me a code.rar so i can research it. I'm going crazy with this!!!


Solution

  • Just declare your Activity A as a launcher Activity in your AndroidManifest.xml and inside your Activity A onCreate() you can simply do this

    private SharedPreferences mSharedPreferences;
    private Editor mEditor;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_a);
    
        mSharedPreferences = getSharedPreferences("yourPrefsFileName", Context.MODE_PRIVATE));
        mEditor = mSharedPreferences.edit();
    
        if (mSharedPreferences.getBoolean("isfirstTime", true)) {
            mEditor.putBoolean("isFirstTime",false);
            mEditor.apply();
        }else{
             startActivity(new Intent(this, ActivityB.class));
             overridePendingTransition(0, 0);
             finish();
          }
    }