0

I'm doing a videogame. I wanted the application to have 3 screens. The presentation screen, the play screen, and the end screen.

I know that an activity can be started with an intent, but my problem is that in doing so, the last activity would be stacked, allowing the user to come back to the previous activity (or screen).

Is there a way to avoid this ?

Esteban Filardi
  • 726
  • 3
  • 16
  • 30

2 Answers2

2

use the finish() method inside the activity you want to close.

Abdallah Alaraby
  • 2,222
  • 2
  • 18
  • 30
1

Although others have covered that you can simply call the finish() method to close down an activity if you do not want your user to be able to return to it, there is another issue I wish to cover quickly.

The Android Design Principles, or more specifically the Navigation Principles tell us that we should not be messing around with the default behaviour of the back button too much. A direct quote from the guide;

Consistent navigation is an essential component of the overall user experience. Few things frustrate users more than basic navigation that behaves in inconsistent and unexpected ways.

So, instead of preventing your users from being able to return to the entry screen, consider instead a prompt that notifies your user that they will be leaving the game. That way the back button continues to work as they would expect, and your users will not be suddenly dropped from gameplay. You can override the back button like so;

@Override
public void onBackPressed() {
    AlertDialog.Builder alert = new AlertDialog.Builder(this);
    alert.setTitle("Leaving the Game");
    alert.setMessage("Do you want to leave the game? You might lose your progress.");
    alert.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {
            YourActivity.this.finish();
        }
    });
    alert.setNegativeButton("Cancel", null );
    alert.show();
}

Also, as a note, if you choose to simply close the previous Activity using finish(), the back button will then drop the user out of the app entirely because there is no Activity to go back to.

Rudi Kershaw
  • 12,332
  • 7
  • 52
  • 77