应用程序在后台运行时(平台暂停)未触发离子事件

时间:2020-06-06 16:38:10

标签: android angular cordova ionic-framework capacitor

我想在我的应用进入后台时(例如,按下主屏幕按钮时)执行一些操作。 (我正在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和电容器。

我误会了吗?可能是什么问题?

2 个答案:

答案 0 :(得分:4)

您可以使用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');
        }
    });

})

请注意,您也可以在桌面浏览器中通过切换到另一个标签进行测试。

答案 1 :(得分:0)

好吧...一切正常。问题是,我的两个变体都处于活动状态。