原文: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 提供了兩種型別的喚醒鎖:screen
和 system
。雖然他們被視為獨立不相干的,但也有一種情況是其中某一個生效也暗示著另一個生效的。例如,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 bywakeLockObj.createRequest()
in order to release the wake lock later. If the reference to thewakeLockRequest
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 下可用。