Ionic run function before app closes

2020-07-06 02:32发布

问题:

Is there some kind of function that I can call that listens to whether the app is about to exit, or close or go into the background.. Basically any event that means "the user has stopped using the app"?

I'm my app I build up a 'user log' that tracks the user as they are navigating through the app. Instead of sending little pieces of data constantly to the server as these events occur, I want to send off the whole batch in one go just before the user stops using the app (again, whether that means closing the app completely, sending it to the background etc.)

And lastly, if such a function does indeed exist.. where do you put that function? In your app.js? Or do you have to put that listener in every single controller of your app?

回答1:

You can check this events list from Cordova docs:

https://cordova.apache.org/docs/en/5.4.0/cordova/events/events.html

In particular Pause event:

The event fires when an application is put into the background.

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



回答2:

This code works in ionic2 native app exit and in the browser as well. In the browser, this happens when the URL reload button is pressed or the browser tab is closed.

platform.pause.subscribe(e => {
  this.OptionsSave();
});

window.addEventListener('beforeunload', () => {
  this.OptionsSave();
});