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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29606012/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:39:26  来源:igfitidea点击:

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

javascriptcordovaionic-frameworkionic3ionic4

提问by user1521398

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上使用它,非常感谢

回答by Sithys

Use the two Events "Pause" and "Resume". You will find all Events here in the Apache Cordova Events Documentation.

使用两个事件“ Pause”和“ Resume”。您可以在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 Examplelike 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 Examplelike 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!

试试看,如果您需要进一步的帮助,请告诉我!

回答by Alexander Zakusilo

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 i.e. background
        this.platform.pause.subscribe(() => {
          //Hello pause
        });

        //Subscribe on resume i.e. foreground 
        this.platform.resume.subscribe(() => {
          window['paused'] = 0;
        });
       }
    });
}

回答by George

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;    
})

回答by tfmontague

"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 pauseevent, and when an app becomes active again (brought to the foreground) Cordova fires the resumeevent.

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);

});

回答by user2258168

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 文档

回答by Sampath

17/09/2019

17/09/2019

This works fine for me on Ionic 4app. Tested both on Androidand iOSdevices.

这在Ionic 4应用程序上对我来说很好用。在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');
    });
  }

回答by Inês Gomes

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
        });

回答by Jitendra Dhadavi

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');
     });
}