androidcordovacordova-3

Cordova call function when NOT from resume


I am listening for deviceready and resume events in Cordova.

In my deviceready I only want to call a function, if the app is not starting from a resume.

I.e. can I achieve the below?

document.addEventListener("deviceready", onDeviceReady, false);

function onDeviceReady() {
  document.addEventListener("resume", onResume, false);
  doOnlyWhenNotFromResume();
}

function onResume(event) {
  doOnlyWhenFromResume(event);
}

Cordova version 7.1.0


Solution

  • You could use a boolean flag to avoid the doOnlyWhenNotFromResume() function from being called on resume. If you set this flag when a pause event happens it should work because after pausing the app and "warm-starting" the app again the resume event is triggered.

    Declare this variable in some scope where its accessible for your functions:

    var isResume = false;
    

    And modify your existing code as follows:

    document.addEventListener("deviceready", onDeviceReady, false);
    
    function onDeviceReady() {
      document.addEventListener("resume", onResume, false);
      document.addEventListener("pause", onPause, false);
    
      if (!isResume) {
        doOnlyWhenNotFromResume();
      }
    }
    
    function onResume(event) {
      doOnlyWhenFromResume(event);
    }
    
    function onPause(event) {
      isResume = true;
    }