原文:I’m Awake! Stay Awake with the WakeLock API
做者:Pete LePage 發表時間:December 20, 2018
譯者:西樓聽雨 發表時間: 2018/12/23 (轉載請註明出處)ios
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.git
爲了不消耗電量,許多設備都會在閒置的時候快速進入睡眠模式。雖然這一點不少狀況下都沒問題,但某些應用爲了能完成他們本身的任務,須要保持屏幕常亮或者保持設備處於待機狀態。例如,一款運動記錄應用(屏幕關閉,但系統保持工做),或者一款遊戲,須要使用設備的運動 API 做爲輸入。github
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.web
Wake Lock API (喚醒鎖 API——譯註)爲咱們提供了一種能夠防止設備屏幕變暗和鎖屏以及阻止設備進入睡眠的方式。這種新的能力開啓了一種目前爲止只有本地應用才能作到的新體驗。promise
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 那種只是簡單地讓屏幕保持常亮的方式所存在的缺陷及一系列的安全、隱私問題。安全
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,你的屏幕會頻繁地自動熄滅,這樣便會很難使用。app
Of course, there are plenty of others:ide
固然,除此以外還有許多適用的應用:
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 的幻燈片應用,這類應用的關鍵所在就是在演示的過程當中保持屏幕不熄滅。
步驟 | 狀態 |
---|---|
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,他們值得特別認同。
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。
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.
在某些狀況下,瀏覽器建立喚醒鎖對象可能會失敗,並拋出一個錯誤,例如設備的電量很低。
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 下可用。