Search code examples
javaandroidback-button

Override BackButton while menu is Open


What I am trying to achieve is when the user clicks the back button while the MENU is visible, the menuActual and MENU's state changes from visible to invisible. If the MENU is not open and the user clicks back, then a Toast is displayed saying "Press again to Exit", and if you click back within 2 seconds the application will close.

Code that I have:

@Override
    public void finish() {

    if (MENU.getVisibility() == View.VISIBLE){
        MENU.setVisibility(View.INVISIBLE);
        menuActual.setVisibility(View.INVISIBLE);

    }else {
        if (doubleBackToExitPressedOnce) {
            super.onBackPressed();
            moveTaskToBack(true);

            return;
        }else {

            this.doubleBackToExitPressedOnce = true;
            Toast.makeText(this, "Tap again to Exit!", Toast.LENGTH_SHORT).show();

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

                @Override
                public void run() {
                    doubleBackToExitPressedOnce=false;
                }
            }, 2000);
        }
    }
}`

I have declared boolean doubleBackToExitPressedOnce = false;

The application goes as far as displaying the Toast saying "Press again to Exit", but if back is clicked again the application says "AppName isn't responding"

Struggling to figure out why this is, been a long day.

Thanks!


Solution

  • Do it in onBackPressed like this :

    private boolean doubleBackToExitPressedOnce = false;
    private Handler handler;
    private Runnable runnable;
    
    @Override
    public void onBackPressed() {
        if (MENU.getVisibility() == View.VISIBLE) {
            MENU.setVisibility(View.INVISIBLE);
            menuActual.setVisibility(View.INVISIBLE);
            return;
        }
    
        if (!doubleBackToExitPressedOnce) {
            doubleBackToExitPressedOnce = true;
            Toast.makeText(this, "Tap again to Exit!", Toast.LENGTH_SHORT).show();
    
            handler = new Handler();
            handler.postDelayed(runnable = new Runnable() {
    
                @Override
                public void run() {
                    doubleBackToExitPressedOnce = false;
                }
            }, 2000);
            return;
        }
    
        // Removes the callBack
        handler.removeCallbacks(runnable);
    
        // Replace this next line with finishAffinity() if you want to close the app.
        super.onBackPressed();
    }