簡體   English   中英

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

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

我在我的 Ionic 4 應用程序中工作,當用戶在移動后退按鈕上單擊 2 次時,它應該關閉應用程序,但這並沒有發生。

這是我的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();
  }

當我在首頁(Tab1)上時這是有效的,當我在其他標簽上時它不起作用並且不會進入頭版。

我認為問題出在我的 ( outlet && outlet.canGoBack())因為這不起作用。 我正在使用選項卡主題,當用戶沒有其他選項卡並單擊硬件后退按鈕時,我可以將路由發送到主選項卡。

我正在使用 Ionic 4 標簽主題。

任何幫助深表感謝。

嘗試這個:

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

並在構造函數中調用這個函數。 這解決了我的問題,因為我使用的是標簽主題和outlet.pop(); 沒有工作。 所以我嘗試了這個方法。

這樣做。

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

  });
}

為了回應@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(); }

那是因為您在平台准備就緒之前調用了 registerBackButtonAction。 平台准備好后,您必須訂閱后退按鈕。 一個接近:

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

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

您也可以嘗試以下代碼片段,

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

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

試試這個

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