ionic android 双击退出

app.component.ts

import { Component } from '@angular/core';
import { Platform , ToastController, App ,Tabs,NavController } from 'ionic-angular';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';

import { TabsPage } from '../pages/tabs/tabs';
// import { NativeService } from "../provider/NativeService";

@Component({
  templateUrl: 'app.html'
})
export class MyApp {
  rootPage:any = TabsPage;
  backButtonPressed: boolean = false;
  constructor(
    public platform: Platform, 
    statusBar: StatusBar, 
    splashScreen: SplashScreen,
    // private nativeService:NativeService,
    public appCtrl: App, 
    public toastCtrl: ToastController
  ) {
    platform.ready().then(() => {
      // Okay, so the platform is ready and our plugins are available.
      // Here you can do any higher level native things you might need.
      statusBar.styleDefault();
      splashScreen.hide();

      // this.nativeService.detectionUpgrade();//检查app是否升级
      this.registerBackButtonAction(this.rootPage);//注册返回按键事件

    });
  }
  registerBackButtonAction(tabRef: Tabs): void {
    
    //registerBackButtonAction是系统自带的方法
    this.platform.registerBackButtonAction(() => {
      //获取NavController
      let activeNav: NavController = this.appCtrl.getActiveNavs()[0];
      //如果可以返回上一页,则执行pop
      if (activeNav.canGoBack()) {
        activeNav.pop();
      } else {
        this.showExit()
      }
    });
  }
    //退出应用方法
    private showExit(): void {
      //如果为true,退出
      if (this.backButtonPressed) {
        this.platform.exitApp();
      } else {
          //第一次按,弹出Toast
          this.toastCtrl.create({
              message: '再按一次退出应用',
              duration: 2000,
              position: 'bottom'
          }).present();
        //标记为true
        this.backButtonPressed = true;
        //两秒后标记为false,如果退出的话,就不会执行了
        setTimeout(() => this.backButtonPressed = false, 2000);
      }
    }
}

你可能感兴趣的:(ionic android 双击退出)