20

请在下面找到 Android 硬件后退按钮操作的代码ionic3。由于Ionic4使用角度路由进行导航,后退按钮将如何发生弹出事件?如果我们想跳到最后一页,我们可以使用下面的代码this.navCtrl.goBack('/products');。但是我们如何将它用于 android 硬件后退按钮操作ionic4呢?

Ionic3 硬件后退按钮动作

this.platform.registerBackButtonAction(() => {
    let activePortal = this.ionicApp._loadingPortal.getActive() ||
        this.ionicApp._modalPortal.getActive() ||
        this.ionicApp._toastPortal.getActive() ||
        this.ionicApp._overlayPortal.getActive();
    if (activePortal) {
        activePortal.dismiss();
    } else {
        if (this.nav.canGoBack()) {
            ***this.nav.pop();***
        } else {
            if (this.nav.getActive().name === 'LoginPage') {
                this.platform.exitApp();
            } else {
                this.generic.showAlert("Exit", "Do you want to exit the app?", this.onYesHandler, this.onNoHandler, "backPress");
            }
        }
    }
});
4

6 回答 6

23

更新:这已在v4.0.0-beta.8 (dfac9dc)中修复


相关: ionic4 替代registerBackButtonAction


这在GitHubIconic ForumTwitter 上
进行了跟踪 在 没有官方修复之前,您可以使用下面的解决方法。


使用platform.backButton.subscribe(参见此处 platform.backButton.subscribeWithPriority(0, ...) 让 ionic 处理关闭所有模式/警报/... ,当按下它自己的后退按钮和新的路由器控制器一起使用时,代码 ionic 使用,我们得到如下内容:

import { ViewChild } from '@angular/core';
import { IonRouterOutlet, Platform } from '@ionic/angular';
import { Router } from '@angular/router';

//...

/* get a reference to the used IonRouterOutlet 
assuming this code is placed in the component
that hosts the main router outlet, probably app.components */
@ViewChild(IonRouterOutlet) routerOutlet: IonRouterOutlet;

constructor(
  ...
  /* if this is inside a page that was loaded into the router outlet,
  like the start screen of your app, you can get a reference to the 
  router outlet like this:
  @Optional() private routerOutlet: IonRouterOutlet, */
  private router: Router,
  private platform: Platform
  ...
) {
  this.platform.backButton.subscribeWithPriority(0, () => {
    if (this.routerOutlet && this.routerOutlet.canGoBack()) {
      this.routerOutlet.pop();
    } else if (this.router.url === '/LoginPage') {
      this.platform.exitApp(); 

      // or if that doesn't work, try
      navigator['app'].exitApp();
    } else {
      this.generic.showAlert("Exit", "Do you want to exit the app?", this.onYesHandler, this.onNoHandler, "backPress");
    }
  });
}

于 2018-08-07T14:21:39.847 回答
13

试试这个: app.comonent.ts

import { Component, ViewChildren, QueryList } from '@angular/core';
import { Platform, ModalController, ActionSheetController, PopoverController, IonRouterOutlet, MenuController } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';
import { Router } from '@angular/router';
import { Toast } from '@ionic-native/toast/ngx';

@Component({
    selector: 'app-root',
    templateUrl: 'app.component.html'
})
export class AppComponent {

    // set up hardware back button event.
    lastTimeBackPress = 0;
    timePeriodToExit = 2000;

    @ViewChildren(IonRouterOutlet) routerOutlets: QueryList<IonRouterOutlet>;

    constructor(
        private platform: Platform,
        private splashScreen: SplashScreen,
        private statusBar: StatusBar,
        public modalCtrl: ModalController,
        private menu: MenuController,
        private actionSheetCtrl: ActionSheetController,
        private popoverCtrl: PopoverController,
        private router: Router,
        private toast: Toast) {

        // Initialize app
        this.initializeApp();

        // Initialize BackButton Eevent.
        this.backButtonEvent();
    }

    // active hardware back button
    backButtonEvent() {
        this.platform.backButton.subscribe(async () => {
            // close action sheet
            try {
                const element = await this.actionSheetCtrl.getTop();
                if (element) {
                    element.dismiss();
                    return;
                }
            } catch (error) {
            }

            // close popover
            try {
                const element = await this.popoverCtrl.getTop();
                if (element) {
                    element.dismiss();
                    return;
                }
            } catch (error) {
            }

            // close modal
            try {
                const element = await this.modalCtrl.getTop();
                if (element) {
                    element.dismiss();
                    return;
                }
            } catch (error) {
                console.log(error);

            }

            // close side menua
            try {
                const element = await this.menu.getOpen();
                if (element) {
                    this.menu.close();
                    return;

                }

            } catch (error) {

            }

            this.routerOutlets.forEach((outlet: IonRouterOutlet) => {
                if (outlet && outlet.canGoBack()) {
                    outlet.pop();

                } else if (this.router.url === '/home') {
                    if (new Date().getTime() - this.lastTimeBackPress < this.timePeriodToExit) {
                        // this.platform.exitApp(); // Exit from app
                        navigator['app'].exitApp(); // work in ionic 4

                    } else {
                        this.toast.show(
                            `Press back again to exit App.`,
                            '2000',
                            'center')
                            .subscribe(toast => {
                                // console.log(JSON.stringify(toast));
                            });
                        this.lastTimeBackPress = new Date().getTime();
                    }
                }
            });
        });
    }
}

它对我有用,在 ionic v4 beta 中

于 2018-09-15T21:41:14.627 回答
1

这是我在Ionic 5 Project上的工作代码。使用 Cordova/PhoneGap

import {Component} from '@angular/core';
import {ToastService} from './_services/toast.service';

@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html',
  styleUrls: ['app.component.scss']
})
export class AppComponent {
  constructor(private toastCtrl: ToastService) {
    this.backButton();
  }
  backButton() {
      const that = this;
      let lastTimeBackPress = 0;
      const timePeriodToExit = 2000;
      function onBackKeyDown(e) {
          e.preventDefault();
          e.stopPropagation();
          if (new Date().getTime() - lastTimeBackPress < timePeriodToExit) {
              navigator.app.exitApp();
          } else {
              that.presentToast();
              lastTimeBackPress = new Date().getTime();
          }
      }
      document.addEventListener('backbutton', onBackKeyDown, false);
  }
  presentToast() {
    const toast = this.toastCtrl.create({
      message: "Press again to exit",
      duration: 3000,
      position: "middle"
    });
  toast.present();
  }
}

或见:- https://thaaimozhikalvi.com/2020/05/28/ionic-5-double-tab-back-button-to-exit-using-cordova-phonegap/

于 2020-05-28T19:17:49.630 回答
0

这就是我在我的应用程序中的做法(使用 ionic4 开发的适用于 android 应用程序)。所以当用户点击安卓手机时,应用程序退出。

示例代码:

import { Component, AfterViewInit, OnDestroy } from '@angular/core';
import { Platform } from '@ionic/angular';
@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html',
  styleUrls: ['app.component.scss']
})
export class AppComponent implements AfterViewInit, OnDestroy {

  constructor(private platform: Platform) { }
  backButtonSubscription;
  ngAfterViewInit() {
    this.backButtonSubscription = this.platform.backButton.subscribe(() => {
      // add logic here if you want to ask for a popup before exiting
      navigator['app'].exitApp();
    });
  }

  ngOnDestroy() {
    this.backButtonSubscription.unsubscribe();
  }
}

来源:这里

于 2019-10-22T05:34:12.203 回答
0

使用科尔多瓦事件“后退按钮”

document.addEventListener("backbutton", youFunction, false);

我使用 ionic4/vue 并且它有效

于 2020-01-28T16:40:38.327 回答
0

在 Ionic 4 中自定义 Android 后退按钮......每个页面都明智地返回。

第1步: import { Platform, NavController } from '@ionic/angular';

第2步:constructor(public navCtrl: NavController){}

第 3 步:

 private async onBack() {
    this.navCtrl.navigateBack('/project-details');
  }

第4步:

 this.platform.backButton.subscribe(()=>{
        this.onBack();
      });
于 2020-07-03T16:27:54.053 回答