defold / extension-kaios

Defold native extension for use with KaiOS
MIT License
3 stars 4 forks source link

Add the visibilityChange listener and document.visiblityState info to API extension #3

Open subsoap opened 3 years ago

subsoap commented 3 years ago

This info is useful for detecting the current lifecyle of the KaiOS app. Either for saving data or doing things like stopping audio from playing.

document.addEventListener('visibilityChange', function() {
  if(document.visiblityState == 'hidden') {
    //enter code for pausing refresh
  }
  else if(document.visibilityState == 'visible') {
    //resume refresh
  }
});

App sound continues playing when the device is locked and/or the display is off. Many developers forget to monitor the visibility of their Apps, and Apps background music still plays when Apps are hidden, for example, stay in the background, or screen display off, or screen locked. Add an event listener on “visibilitychange” and from there if it is not visible, mute the game. If it is visible then check if it has focus. If it has the focus then unmute, else continuously check if it gained focus under these conditions and then unmute it. Click here to learn how it could be achieved. You can also refer to this medium article by a KaiOS developer.

https://developer.mozilla.org/en-US/docs/Web/API/Document/visibilitychange_event

https://developer.mozilla.org/en-US/docs/Web/API/Document/visibilityState

TODO actually test this to see if document.visiblityState == 'hidden' triggers when screen goes off lets us save data gracefully, I wonder if the engine will stop sim and prevent us to actually save.

subsoap commented 3 years ago

If engine sim halts while it's hidden then for stopping audio a separate JS check may be necessary depending on how the audio was played.

subsoap commented 3 years ago

If engine sim does halt while it's hidden then it would be better user experience to have a save system which Defold communicates with but is mostly on the JS side which and then save/load user data while these states are detected to better ensure user data is safely saved in most situations. Need to test to know.