Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 -

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?

like image 366
Dr. Atul Tiwari Avatar asked Nov 25 '15 07:11

Dr. Atul Tiwari


People also ask

How do I close an app from pressing the back button?

In order to check when the 'BACK' button is pressed, use onBackPressed() method from the Android library. Next, perform a check to see if the 'BACK' button is pressed again within 2 seconds and will close the app if it is so. Otherwise, don't exit.

What is Android App fragment?

A Fragment represents a reusable portion of your app's UI. A fragment defines and manages its own layout, has its own lifecycle, and can handle its own input events. Fragments cannot live on their own--they must be hosted by an activity or another fragment.

What is fragment back stack in Android?

Calling addToBackStack() commits the transaction to the back stack. The user can later reverse the transaction and bring back the previous fragment by pressing the Back button. If you added or removed multiple fragments within a single transaction, all of those operations are undone when the back stack is popped.


2 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 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;
    }
}
like image 157
himanshu1496 Avatar answered Nov 01 '22 21:11

himanshu1496


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();
            }
        }
    }
like image 21
Chinmayee Mishra Avatar answered Nov 01 '22 23:11

Chinmayee Mishra