Android & Webapp, call background refresh when mobile is locked

401 Views Asked by At

For an alert system following a reservation (private use), I would like my webapp to send a notification. I want every X minutes an ajax call is made, checks if there is a new reservation and if so sends the notification. I have no problem for the operation and the sending of the notification unless the mobile is locked.

I have seen several posts on this subject but they are dated. I tried settimetout, setinterval and background-timer, without success.

Maybe today there is a way?

EDIT : To be more clear. My webapp manages to send notifications even when the mobile is locked, but the verification interval seems random. A test with a setInterval of 1 minute, sends me a notification after 2 minutes for example, then 5 minutes later... not always with the same interval.

EDIT 2 : In response to Gowtham K K, I tried using a web worker for the setInterval but it doesn't work when mobile is locked.

Code in my main page :

 if(window.Worker){     
        var myWorker = new Worker("sw2.js");
        myWorker.postMessage(0);
        myWorker.onmessage = function(e){
            var dt = new Date();
            var hm = dt.toISOString().substring(11, 19);
            _test.innerHTML += hm+"<br>";           
        }    
    }

Code in sw2.js

self.onmessage = function(e) {
  self.postMessage(0);  
  init();
}

function init() {
   setInterval(send,60000);
}
function send() {
   self.postMessage(0); 
}
1

There are 1 best solutions below

0
Gowtham K K On

As far as I know, service worker would atleast might solve most of your problem. Service worker is a background worker for a website. It is supported by most modern browsers.

It acts an proxy layer between browser and web server. For example when user laoded web app and then internet got disconnected. At that time you can register in service worker and so when user connects to internet again, you can make the service worker task to run even when the user is not seeing the webpage. Here you can handle push notification inside service worker .

Service worker has its own lifecycle.

In your case you can try running the background timer inside the service worker and handle the push notification.

Some Useful links:

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

https://medium.com/@a7ul/beginners-guide-to-web-push-notifications-using-service-workers-cb3474a17679