title: Android Double Back Press to close the app having fragments
body: <p>I followed <a href="http://stackandroid.com/tutorial/double-back-press-to-exit/" rel="noreferrer">this tutorial</a> and certain similar answers on SO.</p>
  
  <p>My present <code>onBackPressed</code> code is as follows -</p>
  
  <pre><code>private static final int TIME_DELAY = 2000;
  private static long back_pressed;
  
  @Override
  public void onBackPressed() {
      DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
      if (drawer.isDrawerOpen(GravityCompat.START)) {
          drawer.closeDrawer(GravityCompat.START);
      } else {
          int fragments = getFragmentManager().getBackStackEntryCount();
          if (fragments &gt; 0) {
              super.onBackPressed();
          } else {
              if (back_pressed + TIME_DELAY &gt; System.currentTimeMillis()) {
                  super.onBackPressed();
              } else {
                  Toast.makeText(getBaseContext(), "Press once again to exit!",
                          Toast.LENGTH_SHORT).show();
              }
              back_pressed = System.currentTimeMillis();
          }
      }
  }
  </code></pre>
  
  <p>I am adding fragments to back stack like this (and at some places I don't add to back stack) -</p>
  
  <pre><code>private void LoadSignDetailsFragment() {
      Bundle args = new Bundle();
      Fragment fragment = new SignDetailsFragment();
      args.putBoolean("hasValues", true);
      args.putBoolean("showBookmarkedSignsOnly", showBookmarkedSignsOnly);
      args.putInt("sign_id", signId);
      if (fragment != null) {
          FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
          fragment.setArguments(args);
          FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
          fragmentTransaction.setCustomAnimations(R.anim.enter, R.anim.exit, R.anim.pop_enter, R.anim.pop_exit);
          fragmentTransaction.replace(R.id.container_body, fragment);
          fragmentTransaction.addToBackStack(null);
          fragmentTransaction.commit();
      }
  }
  </code></pre>
  
  <p>What I am trying to do is, if there is any fragment in backstack, single <code>onBackPressed</code> migrate to previous fragment. But, if there no Fragment in backstack, it should display Toast for double back press to close the app.</p>
  
  <p>My present code, always shows the Toast, and asks for Double back press irrespective of presence/absence of fragments in backstack. I am unable to figure out why?</p>