Blaze Blaze - 6 months ago 14
Java Question

Exit an app on dialog button click

I am trying to exit an app when ever the user clicks the back button let it display a dialog yes/no button on clicking the yes button let it exit the app including with the registration activity assuming you are on the main activity.

This is my code but it not working

private AlertDialog AskOption()
{
AlertDialog myQuittingDialogBox =new AlertDialog.Builder(this)
.setTitle("Exit")
.setMessage("Are you sure you want to exit?")
// .setIcon(R.drawable.delete)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//at this point i am trying to exit the app
Register reg = new Register();
reg.finish();
finish();
System.exit(0);

}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.create();
return myQuittingDialogBox;

}


when the back button is clicked on the main activity

@Override
public void onBackPressed() {

AlertDialog diaBox = AskOption();
diaBox.show();

}


How do I exit the app from the mainactivity including the register activity on yes button click of the dialog

Answer

Use this code.

  .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int whichButton) {
    //at this point i am trying to exit the app
              Intent intent = new Intent(Intent.ACTION_MAIN);
              intent.addCategory(Intent.CATEGORY_HOME);
              intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
              startActivity(intent);
              finish();
              System.exit(0);

               }   
           })

Note :

if you used Intent.FLAG_ACTIVITY_CLEAR_TOP then it can clean the History of Activity.

Comments