ionic4 实现双击返回退出APP

最近升级到ionic4 在实现双击返回键退出APP的功能时发现platform.exitApp()方法不存在ionic4 实现双击返回退出APP_第1张图片然后就是苦逼的百度,发现大都是ionic3及以前的方法,引入的是ionic-angular资源实现的退出,于是替换@ionic/angular为ionic-angular是的各种报错崩溃...

 

黄天不负有心人,最终ionic4实现退出的方法还是被我找到了,废话不多说看实现代码:

首先感谢:https://stackoverflow.com/questions/55024239/my-hardware-back-button-action-is-not-working-in-ionic-4?noredirect=1&lq=1

import { Component } from '@angular/core';

import { Router } from '@angular/router';

import { Platform, AlertController } from '@ionic/angular';

import { SplashScreen } from '@ionic-native/splash-screen/ngx';

import { StatusBar } from '@ionic-native/status-bar/ngx';




@Component({

  selector: 'app-root',

  templateUrl: 'app.component.html'

})

export class AppComponent {

  constructor(

    private platform: Platform,

    private splashScreen: SplashScreen,

    private statusBar: StatusBar,

    private router: Router,

    private alertController: AlertController

  ) {

    this.initializeApp();

    this.backButtonEvent();

  }



  initializeApp() {

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

      this.statusBar.styleDefault();

      this.splashScreen.show();

    });

  }

  lastTimeBackPress = 0;

  timePeriodToExit = 2000;

  backButtonEvent() {

    this.platform.backButton.subscribe(() => {

      if (this.router.url == 'home') {

        if (new Date().getTime() - this.lastTimeBackPress < this.timePeriodToExit) {

          navigator['app'].exitApp(); //退出APP

        } else {

          //this.presentAlertConfirm();

          this.lastTimeBackPress = new Date().getTime();//再按

        }

        // navigator['app'].exitApp(); //ionic4 退出APP的方法

      }

    })

  }

  async presentAlertConfirm() {

    const alert = await this.alertController.create({

      // header: 'Confirm!',

      message: '您要退出APP吗?',

      buttons: [

        {

          text: '取消',

          role: 'cancel',

          cssClass: 'secondary',

          handler: (blah) => {

          }

        }, {

          text: '退出',

          handler: () => {

            navigator['app'].exitApp();

          }

        }

      ]

    });

    await alert.present();

  }

}


demo地址:https://github.com/HuXiaofu/ionic4Demo

你可能感兴趣的:(MyAngular2+)