Micah Williamson Micah Williamson - 1 year ago 136
Android Question

How to Save State on Cordova App Exit?

I have a cordova (ionic) app that facilitates entering a lot of form data. This form data is saved to localStorage until it is ready to be published.

So keep the app quick I am not saving to the disk everytime and input changes. I am saving when the user navigates away from the page.

The problem I'm having is that the user may enter a lot of data on one page, and close the app without navigating. This is an obvious use case but I'm not sure how to get in front of it without frequently going back to the disk.

Is there a way I can quickly save when the app is exited? I know I can listen to the "pause" event in cordova apps but is that the same when the app is exited? Does an exit emit "pause" ?

If not, what are some strategies for handling this?

Answer Source

The pause event fires when the native platform puts the application into the background, typically when the user switches to a different application. Source

The pause event is the only way to let you know your app is being put in the background. On some mobile platforms you don't even have the possibility to exit your app (in iOS for example), as the platform is managing this for you. So listening to the pause event is your only choice as you loose control once the app is paused. Therefore listening to the pause event is the right strategy. See following code snippet:

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

function onPause() {
    // Save the application state here

In detail I have implemented a storage service with a save-method, which is called in the OnPause-handler.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download