$ionicPlatform.registerBackButtonAction 사용

  • $ionicPlatform 을 이용하면 아주 쉽게 Back 버튼을 컨트롤 할 수 있습니다.
  • 아래의 예제는 Back 버튼을 두번 연속으로 누를 경우 앱이 종료되는 예제 입니다.
angular.module('Sample', ['ionic', 'ngCordova', 'Controllers'])
.run(function($ionicPlatform, $cordovaToast) {
    $ionicPlatform.ready(function() {
        var backbutton = 0;
        $ionicPlatform.registerBackButtonAction(function (event) {
            if (backbutton == 0) {
                backbutton++;
                $cordovaToast.show('종료하시려면 한번더 눌러주세요.', 'short', 'bottom')
                // 2초 후 리셋
                setTimeout(function(){backbutton=0;}, 2000);
            } else {
                navigator.app.exitApp();    // 앱 종료
            }
        }, 100);
    });
});

위 코드만으로 동작 하지 않을 경우(Admob 광고 등등...의 이유로)

  • 저 같은 경우에는 Admob 광고를 달고 나서 부터 Back 버튼 컨트롤이 되지 않았습니다.
  • 정말 거짓말 안하고 구글링을 미친듯이 반나절은 한 것 같습니다.
  • CordovaActivity.java 파일에 아래의 코드를 추가 해주시면 끝!
public class CordovaActivity extends Activity {
    ... 생략 ...

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (this.appView != null) {

            View webview = this.appView.getView();
            if (webview != null) {
                return webview.dispatchKeyEvent(event);
            }

            return true;
        }

        return false;
    }
}
참고로 CordovaActivity.java 경로는 "프로젝트\platforms\android\CordovaLib\src\org\apache\cordova" 에 있습니다.