Add Native like app exit to ionic

So you want something native like feature to your ionic application. In most of the android application we may see a special feature while user wants to exit or kill the application something like “Press again to exit.

As you know in Android devices, we have a physical back button, at any moment if user wants to close/exit the app, then the user needs to press the back button by staying on the first or initial screen of the app. So In ionic we can do the same.

In the AngularJS’s “RUN” section, we can add ionicPlatform related stuffs. There we need to add this bunch of code, which will be executed during user back button press.┬áIn this bunch of code, i have used the toast plugin of ngCordova/cordova. So you can add your own cordova toast plugin.

.run(function($ionicPlatform, $rootScope, $ionicHistory, $toastPlugin) {
    $ionicPlatform.registerBackButtonAction(function(e){
        if ($rootScope.backButtonPressedOnceToExit) {
            ionic.Platform.exitApp();
        } else if ($ionicHistory.backView()) {
            $ionicHistory.goBack();
        } else {
            $rootScope.backButtonPressedOnceToExit = true;
                $toastPlugin.showToast("Press back button again to exit");
            setTimeout(function(){
                $rootScope.backButtonPressedOnceToExit = false;
            },2000);
        }
        e.preventDefault();
        return false;
    },101);
});

Happy Coding !!!