Exit Application by Clicking the Back Button Twice Android-Java

thumbnail

If you notice, there is a pattern in a lot of Android apps and games when clicking the back button to exit the application. A Toast came up with a message like “Please click BACK again to exit” or any other message to make user notice that they going to leave the apps. Now, you will learn about exit android application when clicking the back button twice in Android-Java but in this tutorial, we will going to implementing it in the hard back button.

We are going to use the previous project. Check the Android navigation drawer with navigation Component in Android-Java post if you haven’t read about it yet.

You need to open DashboardActivity.java

DashboardActivity.java

…
public class DashboardActivity extends AppCompatActivity implements
        NavigationView.OnNavigationItemSelectedListener{

    …
    // index to identify current nav menu item 
    public static int navItemIndex = 0;
    public List<Integer> navItemIndexList; 
    private boolean doubleBackToExitPressedOnce = false;
    private Handler mHandler;
    …
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        …
        mHandler = new Handler();
        navItemIndexList = new ArrayList<Integer>();
        navItemIndexList.add(0);
        …
     }
    @Override
    public void onBackPressed() {
        if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
            drawerLayout.closeDrawer(GravityCompat.START);
            return;
        }
        if (navItemIndexList.size()<=1){
            if (doubleBackToExitPressedOnce) {
                super.onBackPressed();
                return;
            }
            this.doubleBackToExitPressedOnce = true;
            Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show();

            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    doubleBackToExitPressedOnce = false;
                }
            }, 2000);
        } else {
            navItemIndexList.remove(navItemIndexList.size()-1);
            super.onBackPressed();
        }
    }
}

Run and test the app then you should be able to see the app as below.

Back To Top