Create a button to exit the app

Asked

Viewed 10,833 times

1

I created this code to close app for it instead of closing reboot. I have Mainactivity and the first one has a splash screen. What I have to change .

public void existeapp (View View ){ existeapp(); }

private void existeapp() {
    AlertDialog.Builder builder = new AlertDialog.Builder(Main2Activity.this);
    builder.setMessage("Do you want to exit?");
    builder.setCancelable(true);
    builder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            finish();
            System.exit(0);

        }
    });
    builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();

        }
    });
    AlertDialog alert = builder.create();
    alert.show();

}

2 answers

1


One solution is to use this.finishAffinity(), but I believe it would only work at Activity Launcher. According to the documentation, this method closes the current Activity and all below the stack.

  • thank you very much xD

0

On Android has no way to "close" effectively an application, only who does it is the operating system.

What you can do is tell the system that you want to finish all the Activitys of your application, it will continue to be shown in the list of recent apps, but when you open it will start from Activity Launcher.

In API’s 16+

To do so remove the System.exit(0); and replace the finish() for finishAffinity()

In Api’s 11+

Replace everything with an Intent creation code with the NEW_TASK and CLEAR_TASK flags.

Your method will then remain :

16+

        @Override
        public void onClick(DialogInterface dialog, int which) {
            finishAffinity();

        }

11+

    @Override
    public void onClick(DialogInterface dialog, int which) {
        Intent intent = new Intent(this, ClasseInicial.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |    Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);
        finish();

    }
  • Thank you very much, you’ve helped me a lot :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.