Reputation: 4371
Hi I made a modification in my app which is I want to close my app after clicking the back button. This might sound common right? but this is what exactly happens to my app. I have 3 screens: Start Page, Game Page and Score Page. after pressing the start button from the Start page it will start the Game Page Intent. After finishing the game the Game Page will then move the intent into Score Page and when the back button is pressed from the Score Page, the intent will be passed on the Start Page like this:
Now after I go back to the Start Page when I pressed the back button again instead of exiting the app it will just go back to the Score Page and again If I pressed the back button it will go to the Start Page again making an endless loop. I placed this code to my Start Page but it doesn't solve my problem:
@Override
public void onBackPressed() {
Startup.this.finish();
}
Do I need to change the flow of my intents or there is a possible solution for this one?
Upvotes: 2
Views: 24475
Reputation: 4139
Whenever you called new activity with new intent then write
finish();
after startActivity()
.
Please check after write finish()
when you called new activity.
One another option.
Write launchmode in your manifest
file these activity called only one time
Manifest File -- > <activity android:name="Main" android:launchMode="singleTask" />
Upvotes: 1
Reputation: 15477
in StartPage when startActivity for Game Page do the following
startActivity(intent);//intent for GamePage
finish();
in Game Page when startActivity for Score Page do the following
startActivity(intent);//intent for Score Page
finish();
in Score Page when pressing BackButton do the following
startActivity(intent);//intent for StartPage
finish();
Upvotes: 1
Reputation: 17557
Or you can just use the flag Intent.FLAG_ACTIVITY_CLEAR_TOP when calling the Start page from the Score page.
Intent intent = new Intent(this, StartActivity.class)
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
Upvotes: 7
Reputation: 4330
just add this snippet on your game page
//just after your startActivity(scoreIntent)
this.finish();
this will finish the game activity before launching the score activity. Now, when you want to end the score activity too, do not launch a new intent with start activity, but just end your score activity (this mean, leave the backpressed callback on its default.
this works because if you close game activity at its natural end, the second-topmost activity in your stack will be the start one. This allows you to just end the topmost activity (the score one) to retrieve the start page.
NOTE: this solution works only in your current workflow. if you add another page (example start-game-gameover-score) you need to replicate this behavior in every non-external activity (in the previous example, in game and gameover pages)
Upvotes: 2