Hardware back button issue in Android Lollipop

I declared hardware back button functionality in my service.js. My Hardware back button functions properly in above android lollipop version but in lollipop or below versions its not functioning properly i.e. when i am in login view, there are some input fields. When focus is on that input field and keyboard is open, then i click on hardware back button it directly shows the Exit popup but I required right behavior that is when i click on back button it first closes the keyboard only after that when I again click on back button it will shows the popup alert.

My hardware back button code is as follows

 $ionicPlatform.registerBackButtonAction(function (e) {
          if ($state.current.name === "app.home" || $state.current.name === "login") {
       var confirmPopup= $ionicPopup.confirm({
        title: 'Exit App',
        template: 'Do you want to Exit?',
        cancelText: 'NO',
        okText: 'YES'
    }).then(function(res) {
        if (res) {
   }else if($state.current.name == "forgetpwd" || $state.current.name == "signup"){
            // navigator.app.backHistory();
                 disableBack: true
        //go to home page
        }, 100);//registerBackButton

Please help me if any one have solution for the same.

Thanks In Advance.