繁体   English   中英

Ionic 5 Capacitor 硬件后退按钮结束应用程序

[英]Ionic 5 Capacitor hardware back button ending the app

我在手机和 android studio 上测试我的离子应用程序时遇到问题,当我按下硬件后退按钮时,应用程序立即退出,我尝试了很多解决方案,但它根本行不通,也不会听我编写的任何代码进去。

这是我的尝试

import { Component, Renderer2, ViewChild } from '@angular/core';

import { IonRouterOutlet, Platform } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';
import { TranslateService } from '@ngx-translate/core';
import { Location } from '@angular/common';

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

  @ViewChild(IonRouterOutlet, {static: true}) routerOutlet: IonRouterOutlet
  constructor(
    private platform: Platform,
    private splashScreen: SplashScreen,
    private statusBar: StatusBar,
    private renderer: Renderer2,
    private translate: TranslateService,
    private location: Location
  ) {
    this.initializeApp();
  }

  initializeApp() {
    this.translate.setDefaultLang( localStorage.getItem('default-language') ? localStorage.getItem('default-language') : navigator.language.slice(0, 2) )
    this.platform.ready().then(() => {
      this.statusBar.styleDefault();
      this.splashScreen.hide();
      this.backButtonEvent();
      if (localStorage.getItem('color-theme')) {
        this.renderer.setAttribute(document.body, 'color-theme', localStorage.getItem('color-theme'))
      } else {
        if(window.matchMedia && window.matchMedia('(prefers-color-scheme: light)').matches === true) 
          this.renderer.setAttribute(document.body, 'color-theme', 'light')
        else
          this.renderer.setAttribute(document.body, 'color-theme', 'dark')
      }
    });
  }

  backButtonEvent() {
    this.platform.backButton.subscribeWithPriority(0, async () => {
      if(!this.routerOutlet.canGoBack())
        navigator["app"].exitApp()
      else
        this.location.back()
    });
  }


}

使用@capacitor/app package 以这种方式尝试:

import { App } from '@capacitor/app';

App.addListener('backButton', ({ canGoBack }) => {
  if(canGoBack){
    window.history.back();
  } else {
    App.exitApp();
  }
});

暂无
暂无

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

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