Android Double Back Press to close the app having fragments

android: clicking twice the back button to exit activity
exit app on back pressed android
double press exit in android
o double back pressed android
double back to exit in android studio
double back press to exit kotlin
android back button closes app
double back in android

I followed this tutorial and certain similar answers on SO.

My present onBackPressed code is as follows -

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 > 0) {
            super.onBackPressed();
        } else {
            if (back_pressed + TIME_DELAY > System.currentTimeMillis()) {
                super.onBackPressed();
            } else {
                Toast.makeText(getBaseContext(), "Press once again to exit!",
                        Toast.LENGTH_SHORT).show();
            }
            back_pressed = System.currentTimeMillis();
        }
    }
}

I am adding fragments to back stack like this (and at some places I don't add to back stack) -

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();
    }
}

What I am trying to do is, if there is any fragment in backstack, single onBackPressed migrate to previous fragment. But, if there no Fragment in backstack, it should display Toast for double back press to close the app.

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?

You can refer to below code for your need. If you are not using v4 support fragment, then you have to use getFragmentManager() instead of getSupportFragmentManager() to get the backstack count. Here I am using boolean value to check if back is clicked, if in 2 seconds it is not clicked again, it will become false again.

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

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

            @Override
            public void run() {
                doubleBackToExitPressedOnce = false;
            }
        }, 2000);
    } else {
        super.onBackPressed();
        return;
    }
}

Android Double Back Press to close the app having fragments, Technology. Transcript. 9/7/2019Android Double Back Press to close the app having fragments - Stack Overflowhttps://stackoverflow.com/  nice but can you please tell me how to exit app from fragment with main container class i donot want to go back to main activity i want to close app inside fragment This comment has been minimized.

private boolean doubleBackToExitPressedOnce = true;
    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            if (doubleBackToExitPressedOnce) {
                this.doubleBackToExitPressedOnce = false;
                Toast.makeText(this,"Please click BACK again to exit.", Toast.LENGTH_SHORT).show();
            } else {
                finish();
            }
        }
    }

android-activity - Double back to close application, Android Double Back Press to close the app having fragments - Stack Overflow.​pdf - Free download as PDF File (.pdf), Text File (.txt) or read  What is the press back button double feature in android: After implementing this code activity dose not close by single pressing back button. After pressing back button at single time it will show us a user written toast message that ” Press Back button again to exit activity application.”.

do this in simple way use below code

Boolean doubleBackToExitPressedOnce = false;

@Override
public void onBackPressed() {
    if (doubleBackToExitPressedOnce) {
        super.onBackPressed();

        System.exit(0);

        return;
    }
    this.doubleBackToExitPressedOnce = true;
    Toast.makeText(this, "Please click BACK again to exit",
            Toast.LENGTH_SHORT).show();

}

Double back press to exit android fragment, Android Double Back Press to close the app having I am adding fragments to back stack like this (and at some places I don't add to back  It is very important to first understand how onBackPressed() works by default for fragments The answer is short: it first searches for any added fragment via addToBackStack, if there is one, it does exactly the same as popBackStack() to pop it, otherwise it does the default onBackPressed() for the activity.

add this code in your fragment onCreateView

    view.setOnKeyListener( new OnKeyListener()
{
  private Boolean exit = false;
    @Override
    public boolean onKey( View v, int keyCode, KeyEvent event )
    {
        if( keyCode == KeyEvent.KEYCODE_BACK )
        {
        //logic for identifying double back press, expires after 3 seconds
         if (exit) {
            getActivity().finish(); // finish activity
        } else {
            Toast.makeText(this, "Press Back again to Exit.",
                    Toast.LENGTH_SHORT).show();
            exit = true;
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    exit = false;
                }
            }, 3 * 1000);

        }
            return true;
        }
        return false;
    }
} );

or if you want yo add it in your activity you have to override onBackPressed methhod and add the same code.

example

private Boolean exit = false;

@Override
public void onBackPressed(){

if (exit) {
            finish(); // finish activity
        } else {
            Toast.makeText(this, "Press Back again to Exit.",
                    Toast.LENGTH_SHORT).show();
            exit = true;
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    exit = false;
                }
            }, 3 * 1000);

        }    
}

but it is is recommended to do it in activity other than fragment

Exit android app on back pressed, In this example, we are overriding the default back button action using the onBackPressed() method override. This method will Toast a message for the single back  I have a Welcome Screen Activity that I put android:noHistory="true" in my AndroidManifest.xml file, but pressing the back button kept taking me back to my MainActivity. I also had to override the onBackPressed() method as you suggested in order for my back button to close my app when I am in my Welcome Screen Actiivty.

The way w/o handler:

@Override
public void onBackPressed() { 
    long currentMillis = System.currentTimeMillis();
    if (currentMillis - this.lastPressed < 2000 && getFragmentManager().getBackStackEntryCount() > 0) {
         getFragmentManager().popBackStack();
    } else {
        // show toast if you need
    }
    this.lastPressed = currentMillis;
}

On back button pressed android finish activity, Android Double Back Press to close the app having fragments - Stack Overflow. Many of you may get concerned and feel that you should have deleted that  The first step to create back-sensitive fragments is to define the interface that we can call to notify particular fragments about back-press. It contains only one method onBackPressed () which returns a value that indicates if back-press event was consumed by the fragment. In this example, we use the base class, but you can define it via the

Conditional navigation, Sometimes you want close the entire application in certain back button press. Here best practice is open up the home window instead of exiting application. For​  The user needs to hit Back button AGAIN to close the app. Note. I have personally noticed similar issues on my apps which involve Fragments so what happens is, the MainActivity stays at the 0th index of Android Back stack once it creates the required Fragment. Now, once the user starts tapping Back button, the app would cycle back till the

I followed this tutorial and certain similar answers on SO. My present onBackPressed code is as follows - Double back press to exit. 9 votes · 5 comments. Get back press work only at second press and notify user to press again to exit. raw ·.

So, in the code where you are committing fragment for the first time, which should looks But if you press the Back button on Android, the app navigates away from the web view page COMPLETELY, taking you back to the previous action, and will close the app if the user clicks the back button twice within two seconds. I have a standard container layout in xml, and call the following to the swap fragments in it: Of course by adding it to the back stack it pops when we press back by default, which is just lovely.

Comments
  • See the documentation of getStackEntryAt(int i) and getStackEntryCount() here developer.android.com/reference/android/app/… and modify the below answers by adding some if conditions in onBackPressed()
  • Thanks, from your explanation only, I found out that, I am using v4 support fragment, but by mistake i was using getFragmentManager() instead of getSupportFragmentManager(). After this correction, even my code sample worked. :)
  • Awesome! Have a nice day.
  • how this gonna work ? once user pressed back button the flag will be marked as true, so after some time if he press again the app will exit without prompt
  • on first click flag is true on second click it goes in if condition to close
  • Sorry, your previous solution didn't work for me. I tried with adding the first code sample to one of fragment, which on back pressed, just moved back to another fragment, no Toast displayed. And even for your updated answer, How does both of your code samples identifies, that if there is any fragment in backstack, move to it or else show message for double back press?