代码之家  ›  专栏  ›  技术社区  ›  Arj 1411

在Ionic3与Ionic4中处理硬件后退按钮

  •  6
  • Arj 1411  · 技术社区  · 8 年前

    请在中查找以下Android硬件后退按钮操作的代码 ionic3 . 作为 Ionic4 使用角度路由导航后退按钮的弹出事件将如何发生?如果我们想跳转到最后一页,可以使用以下代码 this.navCtrl.goBack('/products'); . 但是我们如何在 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");
                }
            }
        }
    });
    
    2 回复  |  直到 7 年前
        1
  •  15
  •   Fabian N.    7 年前

    更新: 这是固定的 dfac9dc


    Related: ionic4 replacement for registerBackButtonAction


    这是追踪到的 GitHub ,在 Iconic Forum Twitter
    在正式修复之前,您可以使用下面的解决方法。


    使用 platform.backButton.subscribe (见 here ) platform.backButton.subscribeWithPriority(0, ...) 让ionic处理关闭所有的modals/alerts/。。。 ,ionic在 its own back button is pressed 和新的 router-controller 我们一起得到这样的东西:

    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");
        }
      });
    }
        2
  •  10
  •   Fabian N.    7 年前

    试试这个: 附录组件

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

    这对我很有用,在离子v4测试版

        3
  •  0
  •   Mateen    6 年前

    这就是我在我的应用程序中的工作方式(在android应用程序中使用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();
      }
    }
    

    资料来源: here

        4
  •  0
  •   Ashish    6 年前

    在Ionic4,我尝试了这种方法,它对我很好。

    当视图进入时,我订阅它变量,当它离开时,然后取消订阅。因此,退出按钮的退出应用程序将只针对该特定页面执行。

    constructor(private platform: Platform){}
    backButtonSubscription;
    ionViewWillEnter() {
      this.backButtonSubscription = this.platform.backButton.subscribe(async () => {
      navigator['app'].exitApp();
      });
     }
    }
    ionViewDidLeave() {
     this.backButtonSubscription.unsubscribe();
    }
    
    推荐文章