How do I handle Android's back button properly?

Hello, I am trying to trap the Android back button to always make sure that the last page before it exits the app is the Menu screen.

Let’s first look at the screen:

This is the menu screen. What you see on the left is actually a part of index.html – its not in a separate template file.

In other words, it has no state name associated to it. index.html code is here https://github.com/pliablepixels/zmNinja/blob/master/www/index.html

Now here is how I am trapping the android back button. My original logic that I thought I’d implement was check the state name, and if it tells me I am at my side menu, then I’ll exit the app, else if I am at any other state, I’ll go to the menu

$ionicPlatform.registerBackButtonAction(function (event) {
        console.log("STATE NAME IS " + $ionicHistory.currentStateName());

        if ($ionicHistory.currentStateName() == "whatd do I put here?") {
            $ionicPlatform.exitApp();
            
        } else {
            // do something else
           
        }
}, 100);

My problem is that the menu state is not really a state. When I tap the menu and it shows up, my “state name” is still the last view name.

So how do I handle this situation?

thx

If you just want to check if the sidemenu is open you can try

$ionicSideMenuDelegate.isOpen();

Thats a good idea. The problem I am facing is $ionicSideMenuDelegate.isOpen(); is always returning false.

Here is my code:

$ionicPlatform.registerBackButtonAction(function (event) {
        console.log("STATE NAME IS " + $ionicHistory.currentStateName());
        console.log ("BACK STATE IS "  + $ionicHistory.backTitle());
        console.log ("MENU ON IS " + $ionicSideMenuDelegate.isOpen());
        console.log ("VIEW HISTORY "   + JSON.stringify($ionicHistory.viewHistory()));

        if ($ionicHistory.currentStateName() == "whatd do I put here?") {
            $ionicPlatform.exitApp();

        } else {
            console.log ("GOING BACK STATE");
             $ionicSideMenuDelegate.toggleLeft();
             console.log ("AFTER TOGGLE MENU ON IS " + $ionicSideMenuDelegate.isOpen());
            // do something else

        }
}, 100);

isOpen always prints FALSE, even after I toggle the menu and I can see the menu show up!

Welp, if you only have 1 sidemenu (if you have 2 you should use getByHandle().isOpen()) and this doesn’t work I guess you could set a variable to true manually when exposing the sidemenu and to false when closing it.