简体   繁体   English

如何在 ionic/cordova/phonegap 中检查在前台或后台运行的应用程序

[英]how to check app running in foreground or background in ionic/cordova/phonegap

Is there any way to check whether the app is running in foreground or background in ionic/cordova/phonegap, I need to use it on android and ios, thanks a lot有什么方法可以检查应用程序是在 ionic/cordova/phonegap 中运行在前台还是后台,我需要在 android 和 ios 上使用它,非常感谢

Use the two Events " Pause " and " Resume ".使用两个事件“ Pause ”和“ Resume ”。 You will find all Events here in the Apache Cordova Events Documentation .您可以在Apache Cordova 事件文档 中找到所有事件。

Event - Pause:事件 - 暂停:

  • The pause event fires when the native platform puts the application into the background, typically when the user switches to a different application.当本机平台将应用程序置于后台时,通常会在用户切换到不同的应用程序时触发 pause 事件。

Event - Resume活动 - 恢复

  • The resume event fires when the native platform pulls the application out from the background.当本机平台从后台拉出应用程序时,将触发 resume 事件。

You can add an Eventlistener for that into your code.你可以在你的代码中添加一个事件监听器。 For those two Events that would be:对于这两个事件,将是:

Pause - Quick Example暂停 - 快速示例

document.addEventListener("pause", onPause, false);

function onPause() {
    // Handle the pause event
}

Or Full Example like this:或者像这样的完整示例

<!DOCTYPE html>
<html>
  <head>
    <title>Pause Example</title>

    <script type="text/javascript" charset="utf-8" src="cordova.js"></script>
    <script type="text/javascript" charset="utf-8">

    // Wait for device API libraries to load
    //
    function onLoad() {
        document.addEventListener("deviceready", onDeviceReady, false);
    }

    // device APIs are available
    //
    function onDeviceReady() {
        document.addEventListener("pause", onPause, false);
    }

    // Handle the pause event
    //
    function onPause() {
    }

    </script>
  </head>
  <body onload="onLoad()">
  </body>
</html>

Resume - Quick Example简历 - 快速示例

document.addEventListener("resume", onResume, false);

function onResume() {
    // Handle the resume event
}

Or Full Example like this或者像这样的完整示例

<!DOCTYPE html>
<html>
  <head>
    <title>Resume Example</title>

    <script type="text/javascript" charset="utf-8" src="cordova.js"></script>
    <script type="text/javascript" charset="utf-8">

    // Wait for device API libraries to load
    //
    function onLoad() {
        document.addEventListener("deviceready", onDeviceReady, false);
    }

    // device APIs are available
    //
    function onDeviceReady() {
        document.addEventListener("resume", onResume, false);
    }

    // Handle the resume event
    //
    function onResume() {
    }

    </script>
  </head>
  <body onload="onLoad()">
  </body>
</html>

Try that out and let me know, if you need further help!试试看,如果您需要进一步的帮助,请告诉我!

For Ionic 2 and Ionic 3 the solution is:对于 Ionic 2 和 Ionic 3,解决方案是:

 import { Platform } from 'ionic-angular'; @Component({ template: `OK` }) constructor(public platform: Platform) { platform.ready().then(() => { if (platform.is('cordova')){ //Subscribe on pause ie background this.platform.pause.subscribe(() => { //Hello pause }); //Subscribe on resume ie foreground this.platform.resume.subscribe(() => { window['paused'] = 0; }); } }); }

A small service for Ionic based on Sithys answer:基于 Sithys 的 Ionic 小服务回答:

factory('BackgroundCheck', function($ionicPlatform){
    var service = {};
    var inBackground = false;

    $ionicPlatform.ready(function() {        
        document.addEventListener("resume", function(){inBackground = false;}, false);
        document.addEventListener("pause", function(){inBackground = true;}, false);
    });

    service.isActive = function(){
        return inBackground == false;
    }
    return service;    
})

"Is there any way to check whether the app is running in foreground or background?" “有什么办法可以检查应用程序是在前台还是后台运行?”

Yes.是的。

1) When an app becomes inactive (runs in the background) Cordova fires the pause event, and when an app becomes active again (brought to the foreground) Cordova fires the resume event. 1) 当应用程序变为非活动状态(在后台运行)时,Cordova 会触发pause事件,而当应用程序再次变为活动状态(带到前台)时,Cordova 会触发resume事件。

2) From these events, one can use a variable to store the state as "foreground" or "background". 2)从这些事件中,可以使用变量将状态存储为“前景”或“背景”。

document.addEventListener("deviceReady", function readyCallback() {


    var isAppInForeground = true;


    document.addEventListener("pause", function pauseCallback() {
      isAppInForeground = false;
    }, false);

    document.addEventListener("resume", function resumeCallback() {
      isAppInForeground = true;
    }, false);

});

Using an angular abstraction of ionic.Platform使用ionic.Platform的角度抽象

//The pause event fires when the native platform puts the application
// into the background, typically when the user switches to a different 
// application.
$ionicPlatform.on('pause', function () {
    // Handle event on pause
});
// The resume event fires when the native platform
//  pulls the application out from the background.
$ionicPlatform.on('resume', function () {
    // Handle event on resume
});

Refer to ionic v1 documentation for $ionicPlatform 有关 $ionicPlatform 的信息,请参阅ionic v1 文档

17/09/2019 17/09/2019

This works fine for me on Ionic 4 app.这在Ionic 4应用程序上对我来说很好用。 Tested both on Android and iOS devices.AndroidiOS设备上进行了测试。

app.componet.ts应用程序组件.ts

async initializeApp() {
    await this.platform.ready();

    if (this.platform.is('cordova')) {
        this.setPlatformListener();
   }
 }


  setPlatformListener() {
    this.platform.pause.subscribe(() => {// background
      console.log('In Background');
    });

    this.platform.resume.subscribe(() => {// foreground
      console.log('In Foreground');
    });
  }

You can also use:您还可以使用:

import { Platform, Config, MenuController } from '@ionic/angular';

... ...

constructor( private platform: Platform)

... ...

this.platform.resume.subscribe(() => {
      // Handle event on resume
    });


this.platform.pause.subscribe(() => {
          // Handle event on pause
        });

For those using Capacitor: the App plugin can be used to subscribe to appStateChange events.对于使用 Capacitor 的用户: App插件可用于订阅appStateChange事件。

For Capacitor v2, import and use the plugin with the following code:对于 Capacitor v2,使用以下代码导入和使用插件:

import { Plugins } from '@capacitor/core';

const { App } = Plugins;

App.addListener('appStateChange', (state) => {
  // state.isActive contains the active state
  console.log('App state changed. Is active?', state.isActive);
});

For Capacitor v3+, install @capacitor/app , perform a Capacitor sync ( npx cap sync ), and then import and use the plugin with the following code:对于 Capacitor v3+,安装@capacitor/app ,执行 Capacitor sync ( npx cap sync ),然后使用以下代码导入和使用插件:

import { App } from '@capacitor/app';

App.addListener('appStateChange', ({ isActive }) => {
  console.log('App state changed. Is active?', isActive);
});

Capacitor v4+ provides two additional events called pause and resume that can be subscribed to instead of the appStateChange event: Capacitor v4+ 提供了两个额外的事件,称为pauseresume可以订阅,而不是appStateChange事件:

import { App } from '@capacitor/app';

App.addListener('pause', () => {
  console.log('The app was paused');
});
import { App } from '@capacitor/app';

App.addListener('resume', () => {
  console.log('The app was resumed');
});

According to the Capacitor documentation , the appStateChange event depends on the UIApplication.willResignActiveNotification and the UIApplication.didBecomeActiveNotification on iOS devices, whereas the pause event depends on the UIApplication.didEnterBackgroundNotification , and the resume event depends on the UIApplication.willEnterForegroundNotification on iOS dev.根据Capacitor 文档appStateChange事件取决于 iOS 设备上的UIApplication.willResignActiveNotificationUIApplication.didBecomeActiveNotification ,而pause事件取决于UIApplication.didEnterBackgroundNotificationresume事件取决于 iOS 设备上的UIApplication.willEnterForegroundNotification

I'm unfamiliar with the specifics of how these events differ, but there certainly does seem to be a difference between them (eg see this question ).我不熟悉这些事件有何不同的细节,但它们之间确实存在差异(例如,请参阅此问题)。

On Android, the appStateChange , pause , and resume events all seem to depend on the same native events: onResume and onStop .在 Android 上, appStateChangepauseresume事件似乎都依赖于相同的本机事件: onResumeonStop

If you need to check what the current state of the app is without waiting for any of the afore mentioned events to fire, you can use the getState method on Capacitor v2+.如果您需要在不等待任何上述事件触发的情况下检查应用程序的当前 state 是什么,您可以在 Capacitor v2+ 上使用getState方法。

initializeApp() {
  //Subscribe on pause i.e. background or lock phone
       this.platform.pause.subscribe(() => {
          console.log('pause')
      });
  //Subscribe on pause i.e. background or unlock phone
      this.platform.resume.subscribe(() => {
          console.log('resume');
     });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM