ionic3最小化並且監控到前臺執行和後臺執行

weixin_33968104發表於2018-06-01

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頁面,如下設定

<ion-tabs #myTabs>

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);
    });
  }

相關文章