我想在我的应用程序进入后台时执行一些操作,例如,按下主页按钮时。(我正在安卓设备上进行测试。
我在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
事件。
我正在使用离子9和电容器。
我是不是误会了什么?可能是什么问题?
您可以使用 Capacitor 的应用程序 API 中提供的事件侦听器。
// Import the relevant stuff from Capacitor
import { Plugins, AppState } from '@capacitor/core';
const { App } = Plugins;
然后在您的应用组件类中
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');
}
});
})
请注意,您也可以通过切换到另一个选项卡在桌面浏览器中对此进行测试。
好的... 事情会起作用。问题是,我在代码中激活了两个变体。