是否有可能,在JavaScript中,当屏幕在Android和功放关断检测; iOS的浏览器 [英] Is it possible, in JavaScript, to detect when the screen is turned off in the Android & iOS browsers

查看:435
本文介绍了是否有可能,在JavaScript中,当屏幕在Android和功放关断检测; iOS的浏览器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我跟踪了一些高得离谱的加载时间,我的应用程序的JavaScript报道,发现的Andr​​oid(和iOS)暂停一些JavaScript执行时窗口是在后台或显示器处于关闭状态。

I was tracking down some ridiculously high load times that my app's javascript reported, and found that Android (and iOS) pause some JavaScript execution when the window is in the background or the display is off.

在Android上,我发现我可以使用 window.onfocus 的onblur 事件检测时,应用程序被切换到后台(和js的执行很快就会被暂停,至少在新的脚本),但我不能找到一种方法,当屏幕打开或关闭检测。这可能吗?

On Android, I found that I could use the window.onfocus and onblur events to detect when the app was switching to the background (and js execution would soon be paused, at least for new scripts), but I can't find a way to detect when the screen is turned on or off. Is this possible?

(在Safari上,我有不同之处在于同样的结果聚焦状态的onblur 不可靠的火。)

(On Safari, I had similar results except that onfocus and onblur didn't fire reliably.)

推荐答案

我刚刚发现我的使用情况下,pretty的很好的解决方案:

I just found a pretty good solution for my use case:

function getTime() {
    return (new Date()).getTime();
}

var lastInterval = getTime();

function intervalHeartbeat() {
    var now = getTime();
    var diff = now - lastInterval;
    var offBy = diff - 1000; // 1000 = the 1 second delay I was expecting
    lastInterval = now;

    if(offBy > 100) { // don't trigger on small stutters less than 100ms
        console.log('interval heartbeat - off by ' + offBy + 'ms');
    }
}

setInterval(intervalHeartbeat, 1000);

当屏幕处于关闭状态(或JS暂停出于任何原因),下一个时间间隔被延迟,直到JS继续执行。在我的code,我可以调整计时器的 offBy 量并调用它好。

When the screen is turned off (or JS is paused for any reason), the next interval is delayed until JS execution resumes. In my code, I can just adjust the timers by the offBy amount and call it good.

在快速测试,这似乎在两个安卓4.2.2的浏览器和Safari浏览器在iOS 6.1.3正常工作。

In quick testing, this seemed to work well on both Android 4.2.2's browser and Safari on iOS 6.1.3.

这篇关于是否有可能,在JavaScript中,当屏幕在Android和功放关断检测; iOS的浏览器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆