阅读 206

[译] 谷歌:Wake Lock API 介绍

原文I’m Awake! Stay Awake with the WakeLock API
作者Pete LePage 发表时间:December 20, 2018
译者:西楼听雨 发表时间: 2018/12/23 (转载请注明出处)

什么是 Wake Lock API?

To avoid draining the battery, most devices quickly go to sleep when left idle. While this is fine most of the time, some applications need to keep the screen or the device awake in order to complete their work. For example, a run-tracking app (turns the screen off, but keeps the system awake), or a game, like Ball Puzzle, that uses the device motion APIs for input.

为了避免消耗电量,许多设备都会在闲置的时候快速进入睡眠模式。虽然这一点很多情况下都没问题,但某些应用为了能完成他们自己的任务,需要保持屏幕常亮或者保持设备处于待机状态。例如,一款运动记录应用(屏幕关闭,但系统保持工作),或者一款游戏,需要使用设备的运动 API 作为输入。

The Wake Lock API provides a way to prevent the device from dimming and locking the screen or prevent the device from going to sleep. This capability enables new experiences that, until now, required a native app.

Wake Lock API (唤醒锁 API——译注)为我们提供了一种可以防止设备屏幕变暗和锁屏以及阻止设备进入睡眠的方式。这种新的能力开启了一种目前为止只有本地应用才能做到的新体验。

The Wake Lock API aims to reduce the need for hacky and potentially power-hungry workarounds. It addresses the shortcomings of an older API which was limited to simply keeping the screen on, and had a number of security and privacy issues.

Wake Lock API 旨在消除达到这种效果所需要的极客行为和非常耗电的方案。它消除了旧 API 那种只是简单地让屏幕保持常亮的方式所存在的缺陷及一系列的安全、隐私问题。

推荐使用 Wake Lock API 的场景

RioRun a web app developed by The Guardian that takes you on a virtual audio tour of Rio, following the route of the 2016 Olympic marathon would be a perfect use case. Without wake locks, your screen will turn off frequently, making it hard to use.

RioRun,一款由 The Guardian 所开发的 Web 应用,它可以带你来一次里约音乐之旅,其中跟随 2016 年奥运会的马拉松路线会是最好的案例。如果没有 Wake Lock,你的屏幕会频繁地自动熄灭,这样便会很难使用。

Of course, there are plenty of others:

当然,除此之外还有许多适用的应用:

  • Kiosk-style apps where it’s important to prevent the screen from turning off.

    Kiosk(亭子,报刊亭等。这里指常驻、常侯类的应用——译注)类应用,保持屏幕不熄灭对其来说非常重要。

  • Web based presentation apps where it’s essential to prevent the screen from going to sleep while in the middle of a presentation.

    基于 Web 的幻灯片应用,这类应用的关键所在就是在演示的过程中保持屏幕不熄灭。

该 API 目前的状态

步骤 状态
1. Create explainer(创建解释文档) 已完成
2. Create initial draft of specification(制定规范的初始草案) 已完成
3. Gather feedback & iterate on design(收集反馈并不断迭代设计) 进行中
4. Origin trial(进行 Origin 试验。 Chrome 的一种新特性试验机制,需先申请,申请后只在申请时指定的源——即 origin——下可用。——译注) 未开始
5. Launch(正式发布) 未开始

Note: Big thanks to the folks at Intel, specifically Mrunal Kapade for doing the work to implement this. We depend on a community of committers working together to move the Chromium project forward. Not every Chromium committer is a Googler, and they deserve special recognition!

注意:非常感谢 Intel 的伙伴们,特别是 Marunal Kapade,他帮助实现了这项工作。Chromium 项目的推进离不开社区所有委员们的共同努力。并不是每个 Chromium 项目的委员都是 Googler,他们值得特别认同。

如何使用 Wake Lock API

Dogfood: We’re still working on the Wake Lock API, and it’s only available behind a flag (#enable-experimental-web-platform-features). While in development, bugs are expected, or it may fail to work completely.

现在我们仍然还在开发 Wake Lock API 中,并且它需要开启一个标记(#enable-experimental-web-platform-features)后才能使用。开发过程中,肯定会有 bug 存在,所以它可能会完全无法工作。

Check out the Wake Lock demo and source for the demo.

查看 Wake Lock demo 及其source

Wake lock 的类型

The Wake Lock API provides two types of wake locks, screen and system. While they are treated independently, one may imply the effects of the other. For example, a screen wake lock implies that the app should continue running.

Wake Lock API 提供了两种类型的唤醒锁:screensystem。虽然他们被视为独立不相干的,但也有一种情况是其中某一个生效也暗示着另一个生效的。例如,screen 唤醒锁暗含着应用会持续运行。

screen 唤醒锁

A screen wake lock prevents the device’s screen from turning off so that the user can see the information that’s displayed on screen.

screen 唤醒锁可以阻止设备屏幕熄灭,以便用户可以看到展示在屏幕上的信息。

system 唤醒锁

A system wake lock prevents the device’s CPU from entering standby mode so that your app can continue running.

system 唤醒锁可以阻止设备的 CPU 进入待命模式,以便应用可以保持运行

In order to use the Wake Lock API, we need to create and initialize a wakelock object for the type of wake lock we want. Once created, the promise resolves with a wakelock object, but note, the wake lock isn’t active yet, it’ll need to be activated first.

要使用 Wake Lock API,我们需要先创建并初始化一个 wakelock 对象,创建成功后,promise 会 resolve 一个 wakelock 对象,但请注意,获得的这个对象事还没有激活的,需要先激活。

let wakeLockObj;
if ('getWakeLock' in navigator) {
  try {
    // Create a wake lock for the type we want.
    wakeLockObj = await navigator.getWakeLock('screen');
    console.log('👍', 'getWakeLock', wakeLockObj);
  } catch (ex) {
    console.error('👎', 'getWakeLock', err);
  }
}
复制代码

In some instances, the browser may fail to create the wake lock object, and instead throws an error, for example if the batteries on the device are low.

在某些情况下,浏览器创建唤醒锁对象可能会失败,并抛出一个错误,例如设备的电量很低。

使用 wake lock 对象

We can use the newly created wakeLockObj to activate a lock, or determine the current wake lock state and to receive notifications when the wake lock state is changed.

我们可以使用这个新创建的 wakeLockObj 对象来激活一个锁,或者获取当前唤醒锁的状态以及在这个唤醒锁的状态发生变动时接收到通知。

To acquire a wake lock, we simply need to call wakeLockObj.createRequest(), which creates a new WakeLockRequest object. The WakeLockRequest object allows multiple components on the same page to request their own locks. The WakeLock object automatically handles the requests. The wake lock is released when all of the requests have been cancelled.

要获取一个唤醒锁,我们只需调用一下 wakeLockObj.createRequest() 即可,它会创建一个 WakeLockRequest 对象。页面上多个组件可以请求获取他们自己的锁,WakeLock 对象自动处理这些请求。当所有请求都被取消了之后,这个唤醒锁才会被释放。

let wakeLockRequest;
function toggleWakeLock() {
  if (wakeLockRequest) {
    // Stop the existing wake lock request.
    wakeLockRequest.cancel();
    wakeLockRequest = null;
    return;
  }
  wakeLockRequest = wakeLockObj.createRequest();
  // New wake lock request created.
}
复制代码

Caution: It’s critical to keep a reference to wakeLockRequest created by wakeLockObj.createRequest() in order to release the wake lock later. If the reference to the wakeLockRequest is lost, you won’t be able to cancel the wake lock until the page is closed.

警告:通过 wakeLockObj.createRequest() 创建的 wakeLockRequest 时 ,为了在后期可以释放这个唤醒锁,一定要保留它的一份引用。如果丢失了这个 wakeLockRequest 的引用,在页面关闭前,你都是无法取消掉这个锁的

You can track if a wake lock is active by listening for the activechange event on the WakeLock object.

你可以通过监听这个 wakeLock 对象的 activechange 事件来追踪它的激活状态。

最佳实践

The approach you take depends on the needs of your app. However, you should use the most lightweight approach possible for your app, to minimize your app's impact on system resources.

采用什么样的方式,这要看你的应用来。不过总而言之,你应该采用最可能轻量的方式,以此最小化应用对系统资源的影响。

Before adding wake lock to your app, consider whether your use cases could be solved with one of the following alternative solutions:

在将唤醒锁添加到你的应用中之前,请思考你的这些场景是否可以用以下这些方案来解决:

  • If your app is performing long-running downloads, consider using background fetch.

    如果你的应用需要执行长时间运行的下载任务,可以考虑使用 background fetch

  • If your app is synchronizing data from an external server, consider using background sync.

    如果你的应用需要从服务器同步数据,可以考虑使用 background sync

Note: Like most other powerful web APIs, the Wake Lock API is only available when served over HTTPS.

注意:与其他许多强大的 Web API 一样,Wake Lock API 只在 HTTPS 下可用。

关注下面的标签,发现更多相似文章
评论