Вы находитесь на странице: 1из 5

9/7/2019 Android Double Back Press to close the app having fragments - Stack Overflow

Android Double Back Press to close the app having fragments

I followed this tutorial and certain similar answers on SO.

My present onBackPressed code is as follows -


5
private static final int TIME_DELAY = 2000;
private static long back_pressed;

@Override
1 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?

android android-fragments onbackpressed


By using our site, you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and
our Terms of Service.

https://stackoverflow.com/questions/33910437/android-double-back-press-to-close-the-app-having-fragments 1/5
9/7/2019 Android Double Back Press to close the app having fragments - Stack Overflow
asked Nov 25 '15 at 7:08
Dr. Atul Tiwari
460 2 15 40

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() – rusted brain Nov 25 '15 at 7:41

5 Answers

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
25 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;
}
}

answered Nov 25 '15 at 7:44


himanshu1496
1,548 15 30

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. :) – Dr. Atul Tiwari Nov 25 '15 at 7:55

Awesome! Have a nice day. – himanshu1496 Nov 25 '15 at 7:56

This worked for me. Thank you – NarenderNishad Nov 6 '17 at 7:53

worked really well. Thanks @himanshu1496 – amit pandya Feb 14 at 5:35

By using our site, you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and
our Terms of Service.

https://stackoverflow.com/questions/33910437/android-double-back-press-to-close-the-app-having-fragments 2/5
9/7/2019 Android Double Back Press to close the app having fragments - Stack Overflow

private boolean doubleBackToExitPressedOnce = true;


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

answered Sep 5 '17 at 7:31


Chinmayee Mishra
11 1

do this in simple way use below code

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

answered Nov 25 '15 at 7:12


raj
1,817 9 21

2 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 – droidev Nov 25 '15 at 7:15

on first click flag is true on second click it goes in if condition to close – raj Nov 25 '15 at 7:31

add this code in your fragment onCreateView

0using our site,


By view.setOnKeyListener(
you acknowledge thatnew
youOnKeyListener()
have read and understand our Cookie Policy, Privacy Policy, and
{
our Terms of Service.
private Boolean exit = false;

https://stackoverflow.com/questions/33910437/android-double-back-press-to-close-the-app-having-fragments 3/5
9/7/2019 Android Double Back Press to close the app having fragments - Stack Overflow
@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

edited Nov 25 '15 at 7:26 answered Nov 25 '15 at 7:14


droidev
4,917 8 47 79

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,
By using ourmove to it or
site, you else show message
acknowledge for double
that you have read back press? – Dr.
and understand Atul
our TiwariPolicy
Cookie Nov,25 '15 at Policy
Privacy 7:29 , and
our Terms of Service.

https://stackoverflow.com/questions/33910437/android-double-back-press-to-close-the-app-having-fragments 4/5
9/7/2019 Android Double Back Press to close the app having fragments - Stack Overflow

The way w/o handler:

0 @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;
}

answered May 16 '18 at 8:00


deathangel908
3,055 3 18 40

By using our site, you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and
our Terms of Service.

https://stackoverflow.com/questions/33910437/android-double-back-press-to-close-the-app-having-fragments 5/5

Вам также может понравиться