0

I am currently working on making a game and I want to exit the game on exit button pressed. I tried using:

finish();

System.exit(0);

But its redirecting me to the main screen of the game.

I want to completely exit the game.

Tamir Abutbul
  • 7,301
  • 7
  • 25
  • 53
Coder
  • 1

2 Answers2

0

finish() and System.exit(0) kills the activity not the app and I believe you want to exit from a child activity to another main activity, and there is no internal function that will stop the app, so you need to follow something like below:
In your exit button click:

Intent intent = new Intent(ChildActivity.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("EXIT", true);
startActivity(intent);

Now in your MainActivity include:

public void onCreate(Bundle savedInstanceState) {

    mContext = getApplicationContext();

    super.onCreate(savedInstanceState);

    if (getIntent().getBooleanExtra("EXIT", false)) {
        finish();
        return;
    }
    // your current codes
    // your current codes
}
Jagar
  • 777
  • 9
  • 24
0

You can use method finishAffinity for this.

For API below 16

ActivityCompat.finishAffinity(this)

For API above 16+ us below code:

finishAffinity();

Use System.exit(0) for releasing the resources and exit the application.

Muazzam A.
  • 647
  • 5
  • 17