ionic3监听物理返回键,最小化app

1.与page同级创建文件夹service 创建backButton.service.ts

import {Injectable} from '@angular/core';
import {Platform, ToastController, App, NavController, Tabs} from 'ionic-angular';
import {AppMinimize} from "@ionic-native/app-minimize";

@Injectable()
export class BackButtonService {

  //控制硬件返回按钮是否触发,默认false
  backButtonPressed: boolean = false;

  //构造函数 依赖注入
  constructor(public platform: Platform,
              public appCtrl: App,
              public toastCtrl: ToastController, private appMinimize: AppMinimize) {
  }

  //注册方法
  registerBackButtonAction(tabRef: Tabs): void {

    //registerBackButtonAction是系统自带的方法
    this.platform.registerBackButtonAction(() => {
      //获取NavController
      let activeNav: NavController = this.appCtrl.getActiveNavs()[0];
      //如果可以返回上一页,则执行pop
      if (activeNav.canGoBack()) {
        activeNav.pop();
      } else {
        if (tabRef == null || tabRef._selectHistory[tabRef._selectHistory.length - 1] === tabRef.getByIndex(0).id) {
          //执行退出
          this.showExit();
        } else {
          //选择首页第一个的标签
          tabRef.select(0);
        }
      }
    });
  }

  //退出应用方法
  private showExit(): void {
    //如果为true,退出
    if (this.backButtonPressed) {
      // this.platform.exitApp();
      console.log('最小化');
      this.platform.registerBackButtonAction(() => {
        this.appMinimize.minimize();
      });
      // 返回值
      this.backButtonPressed = false;
    } else {
      //第一次按,弹出Toast
      this.toastCtrl.create({
        message: '再按一次退出应用',
        duration: 2000,
        position: 'top'
      }).present();
      //标记为true
      this.backButtonPressed = true;
      //两秒后标记为false,如果退出的话,就不会执行了
      setTimeout(() => this.backButtonPressed = false, 2000);
    }
  }
}
  1. 在控制台执行
npm install --save @ionic-native/app-minimize

3.在app.module中引用

 providers: [ BackButtonService]

4.在需要监听返回键缩小app的地方调用service

 public translateService: TranslateService,
              public navParams: NavParams


    // 限制安卓物理返回鍵
    this.platform.ready().then(() => {
      this.backButtonService.registerBackButtonAction(null);
    });

官方文档:
1.App Minimize
https://ionicframework.com/docs/native/app-minimize/
2.Platform
https://ionicframework.com/docs/api/platform/Platform/

问题:现在可以监听返回键,但是第一次按返回键是提示再按一次后退出,但是第二次退出时按一次返回键就会退出,有知道的童鞋,麻烦告诉我一下,谢谢

猜你喜欢

转载自blog.csdn.net/u013591091/article/details/80594768