1. 程式人生 > >ionic雙擊返回鍵退出應用

ionic雙擊返回鍵退出應用

  .run(function ($ionicPlatform, $location, $ionicPopup, $ionicHistory, $rootScope, loginService, $state, $timeout) {
    ionic.Platform.ready(function () {
      // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
      // for form inputs)if(),
      if (window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard) {
        cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
        cordova.plugins.Keyboard.disableScroll(true);

      }
      if (window.StatusBar) {
        // org.apache.cordova.statusbar required
        StatusBar.styleDefault();
      }
    });

    var again = false; //判斷是不是第二次    
    // 繫結被硬體被點選的時候的事件
    $ionicPlatform.registerBackButtonAction(function (e) {
      //阻止預設的行為
      e.preventDefault();
      // 兩次退出的時候使用的退出框
      function showExitAlert() {
        // 自定義彈窗
        var myPopup = $ionicPopup.show({
          title: '再點選一次退出應用',
        });
        // 成功彈出,設定again        
        again = true;
        myPopup.then(function (res) {
          // 在彈窗被銷燬的時候執行
          console.log('Tapped!', res);
        });
        $timeout(function () {
          again = false;
          myPopup.close(); // 1秒後關閉彈窗
        }, 1000);
      };
      if (again) {
        ionic.Platform.exitApp();
      }

      // 判斷當前路由是否為各個導航欄的首頁,是的話則顯示提示框
      if ($location.path() == '/tab/home' || $location.path() == '/tab/CRM' || $location.path() == '/tab/work' || $location.path() == '/tab/user-center' || $location.path() == '/tab/cooperate'||$location.path() == '/tab/cooperate') {
        // showConfirm();
        showExitAlert();        
      } else if ($ionicHistory.backView()) {
        $ionicHistory.goBack();
      } else {
        // showConfirm();
        showExitAlert();
      }
      return false;
    }, 501); //101優先順序常用於覆蓋‘返回上一個頁面'的預設行為


  })

這裡最關鍵的在於監聽到點選硬體返回按鈕這個事件。然後我們再進行處理

如果是第二次點選就退出而如果是第一次點選就進行彈窗,並且設定again為true,而如果在1秒內沒有第二次點選就認為過時了,繼續設定agian為false

注意點還有$ionicPopup.show()返回的是一個promise物件。他的第一個函式是在銷燬彈窗的時候才會執行的。