0

In my android application I changed the back button functionality so that it goes to the main screen of my game , now that it's on the main screen how should I exit the whole application with back button ?

public boolean onKeyDown(int keyCode, KeyEvent event)  {
    if (keyCode == KeyEvent.KEYCODE_BACK ) {
          Assets.getInstance().getClick().play(1);
          this.clearScreenStack();
          this.setScreen(new MainMenuScreen(this));
        return true;
    }

    return super.onKeyDown(keyCode, event);
}
melisa zand
  • 211
  • 2
  • 6
  • 16

3 Answers3

1

If you have a mechanism that you can use to see which screen is showing you could do something like this:

public boolean onKeyDown(int keyCode, KeyEvent event)  {
    if (keyCode == KeyEvent.KEYCODE_BACK ) {
        if(mainScreenIsShowing == true){
            //If the main screen is showing let the back button
            //have its default behavior.
            return super.onKeyDown(keyCode, event);
        }else{
            Assets.getInstance().getClick().play(1);
            this.clearScreenStack();
            this.setScreen(new MainMenuScreen(this));
            return true;
        }

    }
    return super.onKeyDown(keyCode, event);
}
FoamyGuy
  • 46,603
  • 18
  • 125
  • 156
0

You can also check if the user enters the back button two times.

boolean backPressed = false;
    public boolean onKeyDown(int keyCode, KeyEvent event)  {
    if (keyCode == KeyEvent.KEYCODE_BACK && !backPressed) {
          Assets.getInstance().getClick().play(1);
          this.clearScreenStack();
          this.setScreen(new MainMenuScreen(this));
          backPressed = true;
        return true;
    }

    backPressed = false;
    return super.onKeyDown(keyCode, event);
}
Michiel Bijlsma
  • 583
  • 5
  • 10
0

This is a debateable subject, but I see nothing wrong or with an application exiting when the back button is pressed. After all, a call to finish() is the default behaviour of the back button. If the activity handling your main screen is at the bottom of your activity stack, then a call to finish() will exit your application.

I propose the following: Let your MainMenuScreen be handled in a separate activity, MainMenuActivity, which is the main activity. finish() other activities when going back to the MainMenuActivity, and handle onKeyDown like this in MainMenuActivity:

public boolean onKeyDown(int keyCode, KeyEvent event)  {
    if (keyCode == KeyEvent.KEYCODE_BACK ) {
        this.finish()
    }
}
Tore Rudberg
  • 1,594
  • 15
  • 16