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

Resume Activity after going to home page


From my MainActivity (Launcher Activity) I press a button to start my GameActivity. I have it so when I hit the Back button in Game Activity, I don't return to my MainActivity and instead return to my home screen. Now when I resume my app it goes to MainActivity instead of returning to GameActivity despite being shown.


Goal

Main Activity -> Game Activity -> Home -> Game Activity

Current Result

Main Activity -> Game Activity -> Home -> Home Activity


A couple things..

  • It works perfectly when I navigate with my home and menu buttons.
  • I have no launchMode in my Manifest

So let us see what I have done!


Main Activity Button Click

 Button startButton = findViewById(R.id.buttonStart);
    startButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(MainActivity.this, GameActivity.class);
            //stops back button to return to add player screen
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);

            startActivity(intent);

        }
    });

Manifest Simplified

 <application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity
        android:name=".MainPage.MainActivity"
        android:label="@string/app_name"
        android:theme="@style/AppTheme.NoActionBar"
        android:screenOrientation="portrait"
        >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".GamePage.GameActivity"
        android:label="@string/title_activity_game"
        android:theme="@style/AppTheme.NoActionBar"
        android:screenOrientation="portrait" />
</application>

Solution

  • In that case, just call finish() right after launching you GameActivity.

    Button startButton = findViewById(R.id.buttonStart);
        startButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, GameActivity.class);
                startActivity(intent);
                finish();
            }
        });
    

    Edit: Update launchMode for your GameActivity also:

    <activity android:name=".GameActivity" android:launchMode="singleInstance">