Search code examples
androidbackgroundexit-code

Not able to close app from Dialog in android


I want to add one functionality in app. I want to close the app while I click on exit button but my button is on Dialog so when I try to use finish() is does not do the same. I just want to close the app.Please help.

// code for the same

    if (v.getId() == R.id.imgLogout) {

        AlertDialog.Builder alertDialog = new AlertDialog.Builder(getContext());
        alertDialog.setMessage("Are you sure you want to exit?");
        alertDialog.setPositiveButton("YES", new OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                // session.logoutUser();
                finish();


            }
        });

// but finish is not working in Dialog


Solution

  • Firstly in your dialog class pass the context of the caller activities say MainActivit.class context

    Now first close the dialog

    //so as to avoid the window leaks as on destroying the activity it's context would also get vanished.

     dialog.dismiss();
    

    and then

    ((Activity) context).finish();