Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling standby on iPad using Javascript

Regarding iPad events, how to determine if/when the iPad is changing from an awake state to a standby state?

What I would like to do is put my Mobile-Safari web app in a locked state whenever the iPad becomes inactive/standby and ask for a PIN when it becomes awake again.

like image 216
rcarrier Avatar asked Feb 09 '11 02:02

rcarrier


2 Answers

I agree that there really ought to be some signal you can hook on to to know when an application goes to sleep and when it wakes up, but you should be able to figure out when Safari wakes up indirectly.

When the webview goes into the background, Safari puts everything in it to sleep. It pauses any video, defers network request, stops updating the UI and pauses all setInterval/setTimeout operations. JS itself will never be aware (as far as I can tell) how these things happened, but it can tell that it has happened. The simplest way to use this is to build a regularly invoked method and check to see if it's been an unexpectedly LONG time since the last update. If you expect something to update every 10 seconds and it's been five minutes, you can be fairly sure that the device has woken up. Here's a quick example I thought up:

    var intTime = new Date().getTime();
    var getTime = function() {
        var intNow = new Date().getTime();
        if (intNow - intTime > 1000) {
            console.log("I JUST WOKE UP")
        }
        intTime = intNow;
        setTimeout(getTime,500);
    };
    getTime();

This will detect when the user has returned from another tab, has dismissed the developer console or brought back Safari from the background. I've set the interval at half a second; you could set it at anything you need, though I think very low values will have concurrency issues and probably will burn the battery down on the device unnecessarily.

like image 134
Andrew Avatar answered Nov 14 '22 18:11

Andrew


The Mobile Safari does not have access to this level of hardware state. The most I think it has is to the accelerator.

like image 1
Daniel A. White Avatar answered Nov 14 '22 17:11

Daniel A. White