【ionic App问题总结系列】ionic点击系统返回键退出App

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq673318522/article/details/53236372

在安卓下,如果不处理系统返回键的事件,那么每次点击返回键,将页面将返回到上一个路由,这种逻辑不符合app的路由逻辑。正确的应该是:当页面到了各个导航页的首页时,此时再按返回键应该提示是否退出app,用户点击确认后退出app。

run()方法中添加下面的方法

$ionicPlatform.registerBackButtonAction(function (e){
        //阻止默认的行为
        e.preventDefault();
        // 退出提示框
        function showConfirm() {
          var servicePopup = $ionicPopup.show({
            title: '提示',
            subTitle: '你确定要退出应用吗?',
            scope: $rootScope,
            buttons: [
              {
                text: '取消',
                type: 'button-clear button-assertive',
                onTap: function () {
                  return 'cancel';
                }
              },
              {
                text: '确认',
                type: 'button-clear button-assertive border-left',
                onTap: function (e) {
                  return 'active';
                }
              },
            ]
          });
          servicePopup.then(function (res) {
            if (res == 'active') {
              // 退出app
              ionic.Platform.exitApp();
            }
          });
        }
         // 判断当前路由是否为各个导航栏的首页,是的话则显示提示框
        if ($location.path() == '/index' || $location.path() == '/product' || $location.path() == '/account' || $location.path() == '/more') {
          showConfirm();
        } else if ($ionicHistory.backView()) {
          $ionicHistory.goBack();
        } else {
          showConfirm();
        }
        return false;
      }, 101); //101优先级常用于覆盖‘返回上一个页面’的默认行为

$ionicPlatform.registerBackButtonAction()

该方法是用来注册系统返回键事件。每次点击只会执行最高优先级的那个行为。比如当页面存在一个modal框的时候,此时点击系统返回键则是关闭modal框,而不是返回上个视图。
ionic官方已经定义了常用的行为的优先级:

  • 返回上个视图=100;
  • 关闭侧栏菜单=150;
  • 关闭Modal=200;
  • 关闭 action sheet=300;
  • 关闭popup=400;
  • 关闭loading=500;

用法如下:
registerBackButtonAction(callback, priority, [actionId])
所以当你要重写ionic官方定义上面那些行为,你只需要设置优先级大于那些行为的优先级即可。比如你要覆盖的是返回上个视图的行为,那么你只需要传入的proirity的值大于100(同时要小于150)即可。

文章首发于我的个人博客: www.iamsuperman.cn

猜你喜欢

转载自blog.csdn.net/qq673318522/article/details/53236372