我想在我的应用进入后台时执行一些操作,例如,在按下主页按钮时。 (我正在 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 类中
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 - 应用程序进入后台时未触发 ionic 事件(平台暂停),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62234807/