Your achievements

Level 1

0% to

Level 2

Tip /
Sign in

Sign in to Community

to gain points, level up, and earn exciting badges like the new
BedrockMission!

Learn more

View all

Sign in to view all badges

SOLVED

"pause" and "resume" events are not executing on Android

andrei_k
Level 2
Level 2

I am unable to use "pause" and "resume" events as described here: Events - Apache Cordova

My test article is working as it should on iOS, but not on Android. On iOS, when I leave the app by opening another app, or put my device to sleep, the "pause" event fires and when I come back, the "resume" event fires. None of this happens on Android.

My basic requirement is to execute some javascript on an interval. But, it doesn't make sense for the code to run when the app is not in the foreground. Has anyone else encountered a similar problem, or can suggest a workaround? (If possible, I'd like to avoid building a custom shell for my app.)

The javascript I'm testing with is:

$(document).ready(function() {

  app.init();

});

var app = {

  init: function() {

    document.addEventListener('deviceready', app.onDeviceReady, false);

  },

  onDeviceReady: function() {

    $("#container").append("<h2>onDeviceReady</h2>");

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

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

  },

  onPause: function() {

    $("#container").append("<h2>onPause</h2>");

  },

  onResume: function() {

    $("#container").append("<h2>onResume</h2>");

  }

};

1 Accepted Solution
andrei_k
Correct answer by
Level 2
Level 2

I determined a workaround to this problem. Although "pause" and "resume" are not fired on Android, the "visibilitychange" event is triggered when the app goes into the background/foreground.

You can use:

document.addEventListener("visibilitychange", myFunction, false);

Inside myFunction function, you can then check the value of document.visibilityState, (it's either "visible" or "hidden") and proceed accordingly.

Note that the "visibilitychange" event does not fire when the app goes in the background/foreground on iOS. So, you need to rely on "pause" and "resume" for iOS and "visibilitychange" for Android.

View solution in original post

1 Reply
andrei_k
Correct answer by
Level 2
Level 2

I determined a workaround to this problem. Although "pause" and "resume" are not fired on Android, the "visibilitychange" event is triggered when the app goes into the background/foreground.

You can use:

document.addEventListener("visibilitychange", myFunction, false);

Inside myFunction function, you can then check the value of document.visibilityState, (it's either "visible" or "hidden") and proceed accordingly.

Note that the "visibilitychange" event does not fire when the app goes in the background/foreground on iOS. So, you need to rely on "pause" and "resume" for iOS and "visibilitychange" for Android.

View solution in original post