ionic3最小化并且监控到前台运行和后台运行

1.安装插件

ionic cordova plugin add cordova-plugin-appminimize
npm install --save @ionic-native/app-minimize

2.建立BackButtonProvider

import { AppMinimize } from '@ionic-native/app-minimize';

export class BackButtonProvider {

  //控制硬件返回按钮是否触发,默认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.appMinimize.minimize();
        } else {
          //选择首页第一个的标签
          tabRef.select(0);
        }
      }
    });
  }

}

3.在tabs.html页面,如下设置

4.在tabs.ts页面

@ViewChild('myTabs') tabRef: Tabs;

  constructor(public backButtonService: BackButtonProvider,
    private platform: Platform) {
    this.platform.ready().then(() => {
      this.backButtonService.registerBackButtonAction(this.tabRef);
    });
  }

5.此处需要注意的是,目前就可以退出最小化了。但是二级页面现在会退出最小化,我们需要如下设置,

  constructor(public navCtrl: NavController, public navParams: NavParams, private platform: Platform, public backButtonService: BackButtonProvider) {

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

6.最后说下如何监听软件是在运行。还是已经最小化了(后台运行)。
我们需要app.component.ts里设置,如下:

 constructor(platform: Platform, statusBar: StatusBar, splashScreen: SplashScreen) {

    platform.ready().then(() => {

      document.addEventListener("resume", () => {
        statusBar.styleDefault();
        splashScreen.hide();
        alert("进入,前台展示"); //进入,前台展示

      }, false);
      // Okay, so the platform is ready and our plugins are available.
      // Here you can do any higher level native things you might need.
      document.addEventListener("pause", () => {

        alert("退出,后台运行"); //退出,后台运行

      }, false);
    });
  }

你可能感兴趣的:(ionic3最小化并且监控到前台运行和后台运行)