5

ionic2/ionic3监听安卓手机返回键

 3 years ago
source link: https://www.longdw.com/2017/06/09/ionic2-ionic3-listen-android-back/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

ionic2/ionic3监听安卓手机返回键

想在安卓手机上实现两次点击返回键才退出程序,花了两天时间终于完美解决,下面放代码。

下面方法可以在app.component.ts中的构造方法中调用

代码段一:

  initializeApp() {
    this.platform.ready().then(() => {
      this.registerBackButtonAction();
    });
  }

代码段二:

registerBackButtonAction() {
      this.platform.registerBackButtonAction(() => {

        if (this.keyboard.isOpen()) {
          this.keyboard.close();
          return;
        }

        const overlay = this.app._appRoot._overlayPortal.getActive();
        if(overlay && overlay.dismiss) {
          overlay.dismiss();
          return;
        }

        const nav = this.app.getActiveNav();
        let activeVC = nav.getActive();
        let page = activeVC.instance;

        // console.log(page);
        // debugger;
        
        if (page instanceof IonTabsPage) {
          this.app.goBack();
          return;
        }
        
        if(nav.canGoBack()){
          nav.pop();
        } else {
          this.showExit();
        }
      });
  }

代码段三:

//双击退出提示框
backButtonPressed: boolean = false;
  showExit() {
    if (this.backButtonPressed) { //当触发标志为true时,即2秒内双击返回按键则退出APP
      this.platform.exitApp();
    } else {
      this.showToast('再按一次退出应用');
      this.backButtonPressed = true;
      setTimeout(() => { //2秒内没有再次点击返回则将触发标志标记为false
        this.backButtonPressed = false;
      }, 2000)
    }
  }

我的项目比较特殊,首页是一个ion-menu,首页点击某个按钮会进入一个ion-tabs构造的页面,暂且叫它IonTabsPage。网上也找了一些关于监听的代码,确实可以,但是一到IonTabsPage页面就无法返回,也就是canGoBack()总是返回false,截止到写这篇博客我还不了解为什么总是返回false。无奈之下只能去判断page,原先代码段二不是那样写的,尤其是

nav.getActive();
//这里的nav我用的是
@ViewChild(Nav) nav: Nav;

这就导致我无法正确的判断类型(instanceof),今天灵光一闪,结合在ionic论坛这里看到看到的资料,修改成了代码段二那样,另外注意在IonTabsPage里面不能用nav.pop()来返回,只能用this.app.goBack(),这也是逛论坛无意中看到的。

上面的app,platform,keyboard按如下方式引入

import { App, Keyboard } from 'ionic-angular';
......

constructor(private app: App, private keyboard: Keyboard) {
    ......
}

记录下这一研究结果,给需要的人。

转载请标明出处:
http://www.longdw.com/ionic2-ionic3-listen-android-back/
本文出自:【Longdw】


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK