MoschDev
MoschDev

Reputation: 671

Android - Close app with System.exit

i want to exit my app with System.exit can anyone help me with any sample code? i am looking to achieve this when the back or home button is pressed.

Upvotes: 1

Views: 5351

Answers (3)

Dhruvil Patel
Dhruvil Patel

Reputation: 2930

you can open dialog on back pressed override method like this.

@Override
        public void onBackPressed() {
            // TODO Auto-generated method stub
            super.onBackPressed();

              DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    switch (which){
                    case DialogInterface.BUTTON_POSITIVE:
                        System.exit(0);
                        break;

                    case DialogInterface.BUTTON_NEGATIVE:

                        dialog.cancel();

                        break;
                    }
                }
            };

            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setMessage("Exit or not ?").setPositiveButton("Yes", dialogClickListener)
                .setNegativeButton("No", dialogClickListener).show();
            }



        }

Upvotes: 1

rekire
rekire

Reputation: 47945

You simply need to add a onclick listener there you can execute the System.Exit call:

((Button) findViewById(R.id.button)).setOnClickListener(new OnClickListener {
    @Override
    public void onClick(View v) {
        System.Exit(0);
    }
});

Upvotes: 0

Raheel Sadiq
Raheel Sadiq

Reputation: 9867

you can do it in back button like this

@Override
public void onBackPressed(){
   super.onBackPressed();
   System.exit(0)
}

Edit: If you are on first activity you dont need to do so, just press back button OS will close your app automatically

Upvotes: 0

Related Questions