使用 Javascript 在 iPad 上处理待机
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4940657/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Handling standby on iPad using Javascript
提问by rcarrier
Regarding iPad events, how to determine if/when the iPad is changing from an awake state to a standby state?
关于 iPad 事件,如何确定 iPad 是否/何时从唤醒状态变为待机状态?
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.
我想做的是在 iPad 处于非活动/待机状态时将我的 Mobile-Safari Web 应用程序置于锁定状态,并在它再次唤醒时要求输入 PIN。
回答by Andrew
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.
我同意确实应该有一些信号可以让您知道应用程序何时进入睡眠状态以及何时唤醒,但您应该能够确定 Safari 何时间接唤醒。
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:
当 webview 进入后台时,Safari 会将其中的所有内容置于睡眠状态。它会暂停任何视频、推迟网络请求、停止更新 UI 并暂停所有 setInterval/setTimeout 操作。JS 本身永远不会知道(据我所知)这些事情是如何发生的,但它可以告诉它已经发生了。使用它的最简单方法是构建一个定期调用的方法,并检查自上次更新以来是否出现了意外的很长时间。如果您希望每 10 秒更新一次并且已经过了 5 分钟,您可以相当确定设备已经唤醒。这是我想到的一个快速示例:
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.
这将检测用户何时从另一个选项卡返回、关闭开发者控制台或从后台带回 Safari。我将间隔设置为半秒;您可以将它设置为您需要的任何值,但我认为非常低的值会产生并发问题,并且可能会不必要地消耗设备上的电池。
回答by Daniel A. White
The Mobile Safari does not have access to this level of hardware state. The most I think it has is to the accelerator.
Mobile Safari 无法访问此级别的硬件状态。我认为它最多的是加速器。
回答by Dom
One possible solution that worked for me is to use
对我有用的一种可能的解决方案是使用
$(window).on('blur', function(){});

