当我按下android设备上的“后退”按钮时,我想关闭该应用程序,但是什么也没有发生,我通过将以下代码写入首页找到了解决方案。主页已加载到我的选项卡中,并且在关闭应用程序时确实起作用。但同时也会关闭所有其他页面的应用程序。请帮忙!
ionViewDidEnter() {
this.subscription = this.platform.backButton.subscribe(() => {
navigator["app"].exitApp();
});
}
ionViewDidLeave() {
this.subscription.unsubscribe();
}
答案 0 :(得分:3)
使用设备后退按钮退出Ionic4应用程序
我尝试了这种方法,对我来说效果很好。
进入视图时,我会将其订阅到变量中,离开视图时将其取消订阅。这样返回按钮上退出的应用程序将仅针对该特定页面执行。
constructor(private platform: Platform){}
backButtonSubscription;
ionViewWillEnter() {
this.backButtonSubscription = this.platform.backButton.subscribe(async () => {
navigator['app'].exitApp();
});
}
}
ionViewDidLeave() {
this.backButtonSubscription.unsubscribe();
}
答案 1 :(得分:0)
这是一个远景,但是最近我一直在寻找类似的东西。
我想要实现的功能是我在一些应用程序中看到的“再次按下退出键”。
这通常是由用户将所有后退按回应用程序的开头触发的。然后再次按下它会显示敬酒警告他们回来,您将退出该应用程序。这样可以防止用户意外退出应用程序。
我知道您正在寻找Ionic 4,这也是我编写的内容,但是我发现的内容被标记为Ionic3。即使它已经更新了2个月,也没有提及Ionic 4。以前,所以我想如果您仍在尝试解决此问题,则应该尝试一下:
仅供参考,我是在Ionic Framework论坛上lengthy discussion的结尾处找到的。
答案 2 :(得分:0)
尝试一下。 在InitialComponent内的AppComponent中添加
this.platform.backButton.subscribeWithPriority(0, () => {
navigator['app'].exitApp();
});
例如
initializeApp() {
this.platform.ready().then(() => {
this.statusBar.styleDefault();
this.splashScreen.hide();
this.platform.backButton.subscribeWithPriority(0, () => {
navigator['app'].exitApp();
});
});
}
答案 3 :(得分:0)
如果您打算仅在主页上和双击后退按钮后退出应用程序,这里是对我有用的解决方案,它是取自 https://www.youtube.com/watch?v=Ntql-JPIQW8 的代码的一部分。>
代码
import { Component, ViewChild } from "@angular/core";
import { IonRouterOutlet, Platform, ToastController } from "@ionic/angular";
import { Location } from "@angular/common";
export class AppComponent {
private lastBackTime: number = 0;
private intervalExitApp: number = 2000;
@ViewChild(IonRouterOutlet, { static: true }) routerOutlet: IonRouterOutlet;
constructor(
private platform: Platform,
private toastController: ToastController,
private location: Location
) {
this.initializeApp();
}
initializeApp() {
this.platform.ready().then(() => {
this.backButtonEvent();
});
}
private backButtonEvent() {
this.platform.backButton.subscribeWithPriority(10, () => {
let currentTime = new Date().getTime();
console.log("currentTime", currentTime);
console.log("lastBackTime -> ", this.lastBackTime);
console.log("Subtraction -> ", currentTime - this.lastBackTime);
if (
!this.routerOutlet.canGoBack() &&
this.lastBackTime &&
this.lastBackTime > 0 &&
currentTime - this.lastBackTime < this.intervalExitApp
) {
navigator["app"].exitApp();
return;
}
if (!this.routerOutlet.canGoBack()) {
this.createToastExitApp();
} else {
this.location.back();
}
console.log("backButton.subscribeWithPriority");
});
}
private createToastExitApp() {
this.toastController
.create({
message: this.getStringFromTranslateService(
"toastMessage.message.exitApp"
),
duration: 2000,
color: "primary",
})
.then((toastEl) => {
toastEl.present();
this.lastBackTime = new Date().getTime();
});
}
}