App does not close after calling finish() in android

Viewed 2786

I am working on an app in which I have one dialog and when I click on the exit button I want to close the app but sometimes app won't finish and return back to my first activity. I do not understand what to do with this.

Code for the same

    AlertDialog.Builder alertDialog = new AlertDialog.Builder(getContext());
        alertDialog.setMessage(context.getResources().getString(R.string.app_close_dialog_msg));
        alertDialog.setPositiveButton(R.string.app_close_dialog_msg_yes, new OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dismiss();
                ((Activity) context).finish();
                //((Activity) context). moveTaskToBack(true);
                System.exit(0);
                android.os.Process.killProcess(android.os.Process.myPid());



            }
        });
4 Answers

Don't

  System.exit(0);
  android.os.Process.killProcess(android.os.Process.myPid()); 

Do

Intent _intentOBJ= new Intent(Intent.ACTION_MAIN);
    _intentOBJ.addCategory(Intent.CATEGORY_HOME);
    _intentOBJ.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    _intentOBJ.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(_intentOBJ);
AlertDialog.Builder alertDialog = new AlertDialog.Builder(getContext());
alertDialog.setMessage(context.getResources().getString(R.string.app_close_dialog_msg));
alertDialog.setPositiveButton(R.string.app_close_dialog_msg_yes, new OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {       
            switch (which) {
                case DialogInterface.BUTTON_POSITIVE:
                    finish();
                    break;
             }
        }

This will do work.

Do not add systems killprocess method instead you have to add finishaffinity() method to exit from application. Below is the code:

AlertDialog.Builder alertDialog = new AlertDialog.Builder(getContext());
   alertDialog.setMessage(context.getResources().

getString(R.string.app_close_dialog_msg));
    alertDialog.setPositiveButton(R.string.app_close_dialog_msg_yes,new

OnClickListener() {
    public void onClick (DialogInterface dialog,int which){
        dismiss();
        ((Activity) context).finishAffinity();

    }
});
Related