ionic3按兩次關閉(typescript語言)

由於是全局事件,所以直接在app.component.ts中寫

頭文件中添加

import { Platform, ToastController} from 'ionic-angular';
import { SettingsProvider } from '../providers/settings/settings';

然後進行定義

 backButtonPressed: boolean = false;  //用於判斷返回鍵是否觸發
  @ViewChild('myNav') nav:Nav;

前端改爲:

<ion-nav [root]="rootPage" [class]="selectedTheme" #myNav [root]="rootPage"></ion-nav>

 構造函數

 constructor(platform: Platform, 
    statusBar: StatusBar, 
    splashScreen: SplashScreen,
    public platform1: Platform, 
    public ionicApp: IonicApp, 
    public settings:SettingsProvider,
    public toastCtrl: ToastController) {
    platform.ready().then(() => {
      statusBar.styleDefault();
      splashScreen.hide();
      this.registerBackButtonAction();//註冊返回按鍵事件
    });
  }

 下面定義的兩個函數,分別是事件和提示框

 registerBackButtonAction() {
    this.platform1.registerBackButtonAction(() => {
      let activePortal = this.ionicApp._modalPortal.getActive();
      if (activePortal) {
        activePortal.dismiss().catch(() => {});
        activePortal.onDidDismiss(() => {});
        return;
      }
      let activeVC = this.nav.getActive();
      let tabs = activeVC.instance.tabs;
      let activeNav = tabs.getSelected();
      return activeNav.canGoBack() ? activeNav.pop() : this.showExit()
    }, 1);
  }

  //雙擊退出提示框
  showExit() {
    if (this.settings.backButtonPressed) { //當觸發標誌爲true時,即2秒內雙擊返回按鍵則退出APP
      this.platform1.exitApp();
    } else {
      this.toastCtrl.create({
        message: '再按一次退出應用',
        duration: 2000,
        position: 'top'
      }).present();
      this.settings.backButtonPressed = true;
      setTimeout(() => this.settings.backButtonPressed = false, 2000);//2秒內沒有再次點擊返回則將觸發標誌標記爲false
    }
  
  }

想設立關閉鍵

setting.html界面 

<button ion-item (click)= "Appdimiss()">
        <ion-icon name="close-circle" item-start color="dark"></ion-icon>
        <ion-label>關閉</ion-label>
</button>

頁面的setting.ts文件 

導入

import { SettingsProvider } from '../../providers/settings/settings';
import { Platform, IonicPage, NavController, NavParams, ViewController,IonicApp,ToastController} from 'ionic-angular';

構造

public settings:SettingsProvider,
public platform1: Platform, 
public toastCtrl: ToastController,

函數 

  Appdimiss(){
    if (this.settings.backButtonPressed) { //當觸發標誌爲true時,即2秒內雙擊返回按鍵則退出APP
      this.platform1.exitApp();
    } else {
      this.toastCtrl.create({
        message: '再按一次退出應用',
        duration: 2000,
        position: 'top'
      }).present();
      this.settings.backButtonPressed = true;
      setTimeout(() => this.settings.backButtonPressed = false, 2000);//2秒內沒有再次點擊返回則將觸發標誌標記爲false
    }
  }

providers裏面的setting.ts,目的是設置爲全局變量,使按鍵和返回鍵行使統一效果

  public backButtonPressed: boolean = false;

這樣無論是按我們設置的按鍵還是返回鍵,在兩秒內按另一個都可以結束程序。

效果圖:

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章