3

Since question is quite similar but I didn't found an exact answer to it. I tried the answer on the link below but it is not working!!

Android Double Back Press to close the app having fragments

Here are my codes:

public interface OnBackPressedListener {

void onBackPressed();
}

Now the fragment:

public class HomeFragment extends Fragment implements View.OnClickListener, OnBackPressedListener{

 boolean doubleBackToExitPressedOnce = false;
@Override
public void onBackPressed() {
    //Checking for fragment count on backstack
    if (getFragmentManager().getBackStackEntryCount() > 0) {
        getFragmentManager().popBackStack();
    } else if (!doubleBackToExitPressedOnce) {
        this.doubleBackToExitPressedOnce = true;
        Toast.makeText(getActivity(),"Tap again to exit.", Toast.LENGTH_SHORT).show();

        new Handler().postDelayed(new Runnable() {

            @Override
            public void run() {
                doubleBackToExitPressedOnce = false;
            }
        }, 2000);
    }
    }

Tried using getSupportFragmentManager() as well, but it is highlighted red. I need to double tap from the fragment (a bottom navigation bar in android) to exit from application.

Panda18
  • 57
  • 1
  • 6

5 Answers5

3

Try this code and it always works.

At top add this

 private boolean isFirstBackPressed = false;

Now inside onBackPressed method add below code.

Add this:

@Override
public void onBackPressed() {
      if (getSupportFragmentManager().getBackStackEntryCount() != 0){
            super.onBackPressed();
      }else{
            if (isFirstBackPressed) {
                  super.onBackPressed();
             } else {
            isFirstBackPressed = true;
            showMessage("Press back again to exit");
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    isFirstBackPressed = false;
                }
            }, 1500);
        }
    }
  }    
halfer
  • 19,824
  • 17
  • 99
  • 186
Sanwal Singh
  • 1,765
  • 3
  • 17
  • 35
1
 private boolean isBackPressedToExit;
private void onBackPressed() {
    if (isBackPressedToExit) {
        finish();
        return;
    }
    isBackPressedToExit = true;
    Utility.toast(TabActivity.this, getString(R.string.msg_press_again_to_exit));
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            isBackPressedToExit = false;
        }
    }, 2000);
}
Prashant Jajal
  • 3,469
  • 5
  • 24
  • 38
1

if you are using NavigationComponent :

 @Override
    public void onBackPressed() {
        if (navController.getCurrentDestination().getId() == navController.getGraph().getStartDestination()) {
            if (doubleBackToExitPressedOnce) super.onBackPressed();
             else onHandlerStart();
            } else super.onBackPressed();
    }

    private void onHandlerStart() {
        doubleBackToExitPressedOnce = true;
        Toast.makeText(this, "Press back again to exit", Toast.LENGTH_SHORT).show();
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() doubleBackToExitPressedOnce = false;
        }, 2000);
    }
mohosyny
  • 962
  • 1
  • 9
  • 19
  • The code you provided may very well produce the desired behavior. However, you could make your answer even better by explaining what was wrong with the code presented in the question. Consider improving your answer ! – Patrick Feb 09 '20 at 13:16
  • Thanks it was helpful, since i was using Navigation Components – Shijilal Jul 02 '21 at 11:15
0

You don't need a handler for this:

@Override
public void onBackPressed() { 
    long currentMillis = System.currentTimeMillis();
    if (currentMillis - this.lastPressed < 2000 && getFragmentManager().getBackStackEntryCount() > 0) {
         getFragmentManager().popBackStack();
    }
    this.lastPressed = currentMillis;
}
deathangel908
  • 8,601
  • 8
  • 47
  • 81
0

Try this it will support your navigation

@Override
public void onBackPressed()
{
    if (navController.getCurrentDestination().getId() == navController.getGraph().getStartDestination()) 
    {
        if (doubleBackToExitPressedOnce){
            super.onBackPressed();
        }
        else {
            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
            builder.setTitle(R.string.app_name);
            builder.setIcon(R.drawable.feather_alert_octagon);
            builder.setMessage("Do you want to exit?")
                    .setCancelable(false)
                    .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id)
                        {

                            finishAffinity();
                            System.exit(0);
                        }
                    })
                    .setNegativeButton("No", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id)
                        {
                            dialog.cancel();
                            backFlag=0;
                        }
                    });
            AlertDialog alert = builder.create();
            alert.show();
        }
    }
    else {
        super.onBackPressed();
    }
}