Sean Hill
Sean Hill

Reputation: 1327

Re-entering app and it's starting from the beginning?

In my MainActivity class, I have a method that starts a new activity and kills the current one:

Intent intent = new Intent(this, NewActivity.class);
startActivity(intent);
finish();

In the new activity, if I press the back button, the app minimizes/closes as expected, but when I re-open the app, instead of showing up in NewActivity, it's gone back to MainActivity!

Why is this so?

Upvotes: 3

Views: 70

Answers (1)

razzledazzle
razzledazzle

Reputation: 6930

Because when it starts afresh, that is, even after you've ended the task, it launches the "Main/Launcher" Activity. You specify this inside the AndroidManifest.

<activity android:name=".MainActivity"
    ...>
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>

Pressing the back button, by default, finishes the current Activity and if no other Activity exist in the current task, the task is known to have ended.

The solution to this is to save some flag or state inside SharedPreferences or persist it somehow to read it again to direct the flow to NewActivity.

In your MainActivity, do something like this:

@Override
protected void onCreate(Bundle savedInstanceState) {
    if(shouldStartNewActivity()) {
        Intent intent = new Intent(this, NewActivity.class);
        startActivity(intent);
        finish();
    } else {
        super.onCreate(savedInstanceState);
    }
}

private boolean shouldStartNewActivity() {
    //Your logic to check if NewActivity should be started directly
}

Upvotes: 2

Related Questions