-2

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

Deepanshi Gupta
  • 127
  • 1
  • 1
  • 7

3 Answers3

1

First Close All Paused Activity. Than You Can Close App. You Remember this activity is last.

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) {                
           finish();
          // context.finish();  if use in fragment
       }
   });
0

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();
batsheva
  • 2,175
  • 1
  • 20
  • 32
0

A very simple way to close app is:

Intent intent = new Intent(Intent.ACTION_MAIN);
                    intent.addCategory(Intent.CATEGORY_HOME);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                    finish();

So in your case try this:

 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();
            Intent intent = new Intent(Intent.ACTION_MAIN);
                    intent.addCategory(Intent.CATEGORY_HOME);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                    finish();


        }
    });
Pulkit
  • 1,020
  • 3
  • 12
  • 26