Create a button to exit the app

0

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

public void existapp (View View) {         existsapp ();     }

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();

}
    
asked by anonymous 03.12.2016 / 00:15

2 answers

0

One solution is to use this.finishAffinity() , but I believe it would only work in the activity launcher. According to documentation , this method closes the current activity and all that are below the stack.

    
03.12.2016 / 00:30
0

In Android there is no way to effectively "close" an application, only the operating system does that.

What you can do is tell the system that you want to end all of your app's Activity, it will still show up in the list of recent apps, but opening it will start from the Activity Launcher.

In 16's APIs

To do this, remove System.exit(0); and replace finish() with finishAffinity()

In Api's 11 +

Replace all with the Intent creation code with the NEW_TASK and CLEAR_TASK Flags.

Your method will then:

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();

    }
    
03.12.2016 / 00:32