应用程序进入后台时未触发离子事件(平台暂停)
Ionic event not triggered when app goes in background (plattform pause)
我想在我的应用进入后台时执行一些操作,例如,在按下主页按钮时。 (我正在 Android 设备上进行测试。)
我在 app.component.ts
中尝试了以下方法:
this.platform.ready().then(() => {
this.platform.pause.subscribe(async () => {
alert("Pause event detected");
//Do stuff here
});
this.platform.resume.subscribe(async () => {
alert("Resume event detected");
//Do stuff here
});
…
我也试过:
App.getState().then((result) => {
alert("state active?" + result.isActive);
});
当应用程序进入后台时(例如,通过按主页按钮),不会触发任何侦听器。但是当我再次启动应用程序时,所有事件都会被触发(在本例中为警报),包括 platform.pause
事件。
我正在使用 Ionic 9 和 Capacitor。
我是不是误会了什么?可能是什么问题?
您可以使用Capacitor's App API中提供的事件侦听器。
// Import the relevant stuff from Capacitor
import { Plugins, AppState } from '@capacitor/core';
const { App } = Plugins;
然后在你的AppComponent中class
this.platform.ready().then(() => {
App.addListener('appStateChange', (state: AppState) => {
if (state.isActive) {
console.log('App has become active');
} else {
console.log('App has become inactive');
}
});
})
请注意,您也可以通过切换到另一个选项卡在桌面浏览器中对此进行测试。
好的...一切正常。问题是,我在代码中激活了两个变体。
我想在我的应用进入后台时执行一些操作,例如,在按下主页按钮时。 (我正在 Android 设备上进行测试。)
我在 app.component.ts
中尝试了以下方法:
this.platform.ready().then(() => {
this.platform.pause.subscribe(async () => {
alert("Pause event detected");
//Do stuff here
});
this.platform.resume.subscribe(async () => {
alert("Resume event detected");
//Do stuff here
});
…
我也试过:
App.getState().then((result) => {
alert("state active?" + result.isActive);
});
当应用程序进入后台时(例如,通过按主页按钮),不会触发任何侦听器。但是当我再次启动应用程序时,所有事件都会被触发(在本例中为警报),包括 platform.pause
事件。
我正在使用 Ionic 9 和 Capacitor。
我是不是误会了什么?可能是什么问题?
您可以使用Capacitor's App API中提供的事件侦听器。
// Import the relevant stuff from Capacitor
import { Plugins, AppState } from '@capacitor/core';
const { App } = Plugins;
然后在你的AppComponent中class
this.platform.ready().then(() => {
App.addListener('appStateChange', (state: AppState) => {
if (state.isActive) {
console.log('App has become active');
} else {
console.log('App has become inactive');
}
});
})
请注意,您也可以通过切换到另一个选项卡在桌面浏览器中对此进行测试。
好的...一切正常。问题是,我在代码中激活了两个变体。