简体   繁体   English

我的硬件“后退按钮操作”在 Ionic 4 中不起作用

[英]My Hardware 'Back Button Action' is not working in Ionic 4

I am working in my Ionic 4 app and When the user clicks 2 times on the mobile back button, then it should close the app but this is not happening.我在我的 Ionic 4 应用程序中工作,当用户在移动后退按钮上单击 2 次时,它应该关闭应用程序,但这并没有发生。

This is my app.component.ts :这是我的app.component.ts

lastTimeBackPress = 0;
timePeriodToExit = 2000;
@ViewChildren(IonRouterOutlet) routerOutlets: QueryList<IonRouterOutlet>;

constructor(){
this.backButtonEvent();
}

backButtonEvent() {
    document.addEventListener("backbutton", () => { 
      this.routerOutlets.forEach((outlet: IonRouterOutlet) => {
        if (outlet && outlet.canGoBack()) {
            outlet.pop();
        } else if (this.router.url === '/tabs/tab1') {
          if (new Date().getTime() - this.lastTimeBackPress < this.timePeriodToExit) {
            navigator['app'].exitApp(); //Exit from app
            } else {
            this.presentAlertConfirm();
            this.lastTimeBackPress = new Date().getTime();
          }
          // navigator['app'].exitApp(); // work for ionic 4
        }
      });
    });
  }

  async presentAlertConfirm() {
    const alert = await this.alertController.create({
      // header: 'Confirm!',
      message: 'Are you sure you want to exit the app?',
      buttons: [
        {
          text: 'Cancel',
          role: 'cancel',
          cssClass: 'secondary',
          handler: (blah) => {
          }
        }, {
          text: 'Close App',
          handler: () => {
            navigator['app'].exitApp();
          }
        }
      ]
    });

    await alert.present();
  }

This is working when I am on front page(Tab1) and when I am on the other tabs it is not working and not going to the front page.当我在首页(Tab1)上时这是有效的,当我在其他标签上时它不起作用并且不会进入头版。

I think the problem is in my ( outlet && outlet.canGoBack()) because this is not working.我认为问题出在我的 ( outlet && outlet.canGoBack())因为这不起作用。 I am using the tab theme and Can I send the route to the main tab when the user is no other tabs and clicks the hardware back button.我正在使用选项卡主题,当用户没有其他选项卡并单击硬件后退按钮时,我可以将路由发送到主选项卡。

I am using Ionic 4 tab theme.我正在使用 Ionic 4 标签主题。

Any help is much appreciated.任何帮助深表感谢。

Try This:尝试这个:

 lastTimeBackPress = 0; timePeriodToExit = 2000; @ViewChildren(IonRouterOutlet) routerOutlets: QueryList < IonRouterOutlet > ; backButtonEvent() { document.addEventListener("backbutton", async() => { try { const element = await this.modalCtrl.getTop(); if (element) { element.dismiss(); return; } } catch (error) { console.log(error); } this.routerOutlets.forEach(async(outlet: IonRouterOutlet) => { if (this.router.url != '/tabs/tab1') { await this.router.navigate(['/tabs/tab1']); } else if (this.router.url === '/tabs/tab1') { if (new Date().getTime() - this.lastTimeBackPress >= this.timePeriodToExit) { await this.presentAlertConfirm(); this.lastTimeBackPress = new Date().getTime(); } navigator['app'].exitApp(); // work for ionic 4 } }); }); }

And call this function in the constructor.并在构造函数中调用这个函数。 This solved my problem because I am using the tabs theme and outlet.pop();这解决了我的问题,因为我使用的是标签主题和outlet.pop(); was not working.没有工作。 So I tried this method.所以我尝试了这个方法。

Do it this Way.这样做。

constructor(private platform: Platform) {
  this.platform.backButton.subscribe(() => {

  });
}

In response to @Raghav comment, I would try it like this:为了回应@Raghav 的评论,我会这样尝试:

 lastTimeBackPress = 0; timePeriodToExit = 2000; @ViewChildren(IonRouterOutlet) routerOutlets: QueryList < IonRouterOutlet > ; constructor(private platform: Platform) { this.backButtonEvent(); } backButtonEvent() { this.platform.backButton.subscribeWithPriority(0, () => { this.routerOutlets.forEach(async(outlet: IonRouterOutlet) => { if (this.router.url != '/tabs/tab1') { await this.router.navigate(['/tabs/tab1']); } else if (this.router.url === '/tabs/tab1') { if (new Date().getTime() - this.lastTimeBackPress >= this.timePeriodToExit) { this.lastTimeBackPress = new Date().getTime(); this.presentAlertConfirm(); } else { navigator['app'].exitApp(); } } }); }); } async presentAlertConfirm() { const alert = await this.alertController.create({ // header: 'Confirm!', message: 'Are you sure you want to exit the app?', buttons: [{ text: 'Cancel', role: 'cancel', cssClass: 'secondary', handler: (blah) => {} }, { text: 'Close App', handler: () => { navigator['app'].exitApp(); } }] }); await alert.present(); }

That is because you are calling the registerBackButtonAction before platform is ready.那是因为您在平台准备就绪之前调用了 registerBackButtonAction。 You have to subscribe to the backbutton after the platform is ready.平台准备好后,您必须订阅后退按钮。 An approaching:一个接近:

this.platform.ready().then(
  () => {
    this.platform.registerBackButtonAction(() => {
      this.platform.exitApp();
   });
  }
);

try this in your app.component.ts在你的 app.component.ts 中试试这个

  lastTimeBackPress = 0;
  timePeriodToExit = 2000;
 @ViewChild(IonRouterOutlet, { static: false }) routerOutlets: IonRouterOutlet

constractor( private router: Router, private alertController: AlertController){this.backbutton()}


backbutton() {
console.log('backbutton')
document.addEventListener("backbutton", () => {
  console.log('backbutton1')
  if (this.routerOutlets && this.routerOutlets.canGoBack()) {
    this.routerOutlets.pop();
  }
  // else if (this.router.url != '/tabs/tabs/tab1') {
  //   this.router.navigate(['/tabs/tabs/tab1']);
  // } 
  else if (this.router.url === '/home') {
    if (new Date().getTime() - this.lastTimeBackPress >= this.timePeriodToExit) {
      this.lastTimeBackPress = new Date().getTime();
      this.presentAlertConfirm();
    } else {
      navigator['app'].exitApp();
    }
  }
});
  }



 async presentAlertConfirm() {
const alert = await this.alertController.create({
  // header: 'Confirm!',
  message: 'Are you sure you want to exit the app?',
  buttons: [{
    text: 'Cancel',
    role: 'cancel',
    cssClass: 'secondary',
    handler: (blah) => { }
  }, {
    text: 'Close App',
    handler: () => {
      navigator['app'].exitApp();
    }
  }]
});
await alert.present();
  }

You can also try the following code snippets,您也可以尝试以下代码片段,

Make a change or add code like this in your app.component.ts fileapp.component.ts文件中进行更改或添加这样的代码

import { Component, ViewChildren, QueryList } from '@angular/core';

import { Platform, IonRouterOutlet, ToastController } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';
import { Router } from '@angular/router';

@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html',
  styleUrls: ['app.component.scss']
})
export class AppComponent {
  //code for exit app
  // set up hardware back button event.
  lastTimeBackPress = 0;
  timePeriodToExit = 2000;

  //code for exit app
  @ViewChildren(IonRouterOutlet) routerOutlets: QueryList<IonRouterOutlet>;
  constructor(
    private platform: Platform,
    private splashScreen: SplashScreen,
    private statusBar: StatusBar,
    private toastController: ToastController,
    private router: Router
  ) {
    this.initializeApp();
    // Initialize BackButton Eevent.
    this.backButtonEvent();
  }

  initializeApp() {
    this.platform.ready().then(() => {
      this.statusBar.styleLightContent();
      this.splashScreen.hide();
    });
  }
  
  // active hardware back button
  backButtonEvent() {
    this.platform.backButton.subscribe(async () => {

      this.routerOutlets.forEach(async (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 {
            const toast = await this.toastController.create({
              message: 'Press back again to exit App.',
              duration: 2000,
              position: 'middle'
            });
            toast.present();
            // console.log(JSON.stringify(toast));
            this.lastTimeBackPress = new Date().getTime();
          }
        }
      });
    });
  }
}

Make a change or add code like this in your home.ts file or where you want to user exit from your app page .在您的home.ts文件中或您希望用户退出应用程序页面的位置进行更改或添加这样的代码。

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

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage {
  public subscription: any;

  constructor(private platform: Platform) { }

  ionViewDidEnter() {
    this.subscription = this.platform.backButton.subscribe(() => {
      navigator['app'].exitApp();
    });
  }

  ionViewWillLeave() {
    this.subscription.unsubscribe();
  }
}

Try this试试这个

import {Component, QueryList, ViewChildren} from '@angular/core';

import {IonRouterOutlet, Platform, ToastController} 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 {Location} from '@angular/common';

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

    lastTimeBackPress = 0;
    timePeriodToExit = 2000;

    // @ts-ignore
    @ViewChildren(IonRouterOutlet) routerOutlets: QueryList<IonRouterOutlet>;

    constructor(
        private platform: Platform,
        private splashScreen: SplashScreen,
        private statusBar: StatusBar,
        private toastController: ToastController,
        private router: Router,
        private location: Location
    ) {
        this.initializeApp();
    }

    initializeApp() {
        this.platform.ready().then(() => {
           
            this.backButtonEvent();
        });
    }

    // active hardware back button
    backButtonEvent() {
        this.platform.backButton.subscribeWithPriority(0, () => {
            this.routerOutlets.forEach(async () => {
                if (this.router.url !== '/tabs/home') {
                    await this.location.back();
                } else {
                    if (new Date().getTime() - this.lastTimeBackPress < this.timePeriodToExit) {
                        navigator['app'].exitApp(); // work in ionic 4
                    } else {
                        const toast = await this.toastController.create({
                            message: 'Press back again to exit App.',
                            duration: 2000,
                            position: 'middle'
                        });
                        toast.present();
                        // console.log(JSON.stringify(toast));
                        this.lastTimeBackPress = new Date().getTime();
                    }
                }
            });
        });
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM