Web API: Screen Wake Lock API для предотвращения выключения экрана устройства
Когда вы смотрите видео на YouTube на своем мобильном устройстве, экран не выключается даже при длительном простое. Это возможно благодаря Screen Wake Lock API.
API блокировки экрана позволяет вашему веб-приложению предотвратить автоматическое выключение экрана устройства. Это особенно полезно для видеоплееров и других приложений, которые должны сохранять экран включенным для продолжительного времени.
При нажатии на кнопку «Начать воспроизведение» вызываем метод navigator.wakeLock.request(), чтобы запросить блокировку экрана, и затем начинаем воспроизведение видео. При нажатии на кнопку «Остановить воспроизведение» мы освобождаем блокировку экрана, если она была запрошена, и останавливаем воспроизведение видео.
const videoPlayer = document.querySelector('#videoPlayer'); const startButton = document.querySelector('#startBtn'); const stopButton = document.querySelector('#stopBtn'); let wakeLock = null; startButton.addEventListener('click', async () => < try < wakeLock = await navigator.wakeLock.request( 'screen' ); videoPlayer.play(); >catch (err) < console.error( 'Ошибка запроса блокировки экрана', err ); >>); stopButton.addEventListener('click', () => < if( wakeLock !== null ) < wakeLock.release(); wakeLock = null; >videoPlayer.pause(); >);
Блокировки
В этом API (версия 1.0) реализована семантика блокировки и разблокировки для ресурса типа «ключ-значение». Поддерживаются следующие операции:
- установка блокировки;
- снятие блокировки.
Если параметр label указан, он должен быть явным значением метки (не подстановочным знаком). Для всех операций это необязательный параметр. Если он не указан, подразумевается любая метка.
Предварительные требования
- Все HTTP-запросы должны пройти проверку подлинности. См. раздел об аутентификации.
- Все HTTP-запросы должны предоставлять явный запрос api-version . См. раздел о версионировании.
Блокировка пары «ключ-значение»
- Требуется: ,
- Необязательно. label
PUT /locks/?label=&api-version= HTTP/1.1
Ответы:
HTTP/1.1 200 OK Content-Type: application/vnd.microsoft.appconfig.kv+json; charset=utf-8"
< "etag": "4f6dd610dd5e4deebc7fbaef685fb903", "key": "", "label": "", "content_type": null, "value": "example value", "created": "2017-12-05T02:41:26.4874615+00:00", "locked": true, "tags": [] >
Если пара «ключ-значение» не существует, возвращается следующий ответ:
HTTP/1.1 404 Not Found
Разблокировка пары «ключ-значение»
- Требуется: ,
- Необязательно. label
DELETE /locks/?label=?api-version= HTTP/1.1
Ответы:
HTTP/1.1 200 OK Content-Type: application/vnd.microsoft.appconfig.kv+json; charset=utf-8"
< "etag": "4f6dd610dd5e4deebc7fbaef685fb903", "key": "", "label": "", "content_type": null, "value": "example value", "created": "2017-12-05T02:41:26.4874615+00:00", "locked": true, "tags": [] >
Если пара «ключ-значение» не существует, возвращается следующий ответ:
HTTP/1.1 404 Not Found
Условная блокировка и разблокировка
Чтобы избегать состояний гонки, используйте заголовки запроса If-Match или If-None-Match . Аргумент etag является частью представления ключа. Если If-Match или If-None-Match опущены, операция является безусловной.
Следующий запрос применяет операцию только в том случае, если текущее представление «ключ-значение» соответствует указанному etag :
PUT|DELETE /locks/?label=&api-version= HTTP/1.1 If-Match: "4f6dd610dd5e4deebc7fbaef685fb903"
Следующий запрос применяет операцию только в том случае, если текущее представление «ключ-значение» существует, но не соответствует указанному etag :
PUT|DELETE /kv/?label=&api-version= HTTP/1.1 If-None-Match: "4f6dd610dd5e4deebc7fbaef685fb903"
Главная
Интерфейс Lock API : существует с Java 1.5.
Базовый интерфейс из lock framework, предоставляющий более гибкий подход по ограничению доступа к ресурсам/блокам нежели при использовании synchronized. Так, при использовании нескольких локов, порядок их освобождения может быть произвольный. Плюс имеется возможность пойти по альтернативному сценарию, если лок уже кем то захвачен.
- synchronized блок полностью находится внутри метода , когда мы можем в Lock API, поставить блокировку в одном методе класса , а разблокировать в другом методе этого класса.
- synchronized блок не поддерживает приоритеты , любой поток может получить блокировку после освобождения метода/блока. Никакого предпочтения не может быть указано, когда в Lock API мы можем , указать свойство приоритетов . Это гарантирует, что самый длинный ожидающий поток получит доступ к блокировке .
- Поток блокируется, если он не может получить доступ к synchronized блоку . Lock API предоставляет tryLock() метод. Поток получает блокировку, только если он доступен и не удерживается каким-либо другим потоком.
- Поток, который находится в состоянии “waiting” для получения доступа к synchronized блоку , не может быть прерван. Lock API предоставляет метод lockInterruptibly() , позволяет прервать заблокированный поток и возобновить выполнение через брошенный java.lang. InterruptedException .
методы интерфейса Lock:
- void *.lock() : получить блокировку, если она доступна; если блокировка недоступна, поток блокируется, пока блокировка не будет снята .
- void *.lockInterruptibly() : похожа на lock(), но позволяет прервать заблокированный поток и возобновить выполнение через брошенный java.lang.InterruptedException .
- boolean *.tryLock() : это неблокирующая версия метода lock () . Он пытается получить блокировку немедленно, возвращает true, если блокировка успешна
- boolean *.tryLock ( long timeout , TimeUnit timeUnit ) : это похоже на tryLock (), за исключением того, что оно ожидает указанное время ожидания, прежде чем отказаться от попытки получить блокировку
- void *.unlock() : разблокирует экземпляр блокировки
- Lock *.readLock() : возвращает блокировку, используемую для чтения .
- Lock *.writeLock() : возвращает блокировку, использованную для записи .
интерфейс Condition :
- await : поток ожидает, пока не будет выполнено некоторое условие и пока другой поток не вызовет методы signal/signalAll. Во многом аналогичен методу wait класса Object
- signal : сигнализирует, что поток, у которого ранее был вызван метод await(), может продолжить работу. Применение аналогично использованию методу notify класса Object
- signalAll : сигнализирует всем потокам, у которых ранее был вызван метод await(), что они могут продолжить работу. Аналогичен методу notifyAll() класса Object
класс ReentrantLock :
Лок на вхождение. Только один поток может зайти в защищенный блок. Класс поддерживает «честную» (fair) и «нечестную» (non-fair) разблокировку потоков. При «честной» разблокировке соблюдается порядок освобождения потоков, вызывающих lock(). При «нечестной» разблокировке порядок освобождения потоков не гарантируется, но, как бонус, такая разблокировка работает быстрее. По умолчанию, используется «нечестная» разблокировка.
класс ReentrantReadWriteLock :
Очень часто используется в многопоточных сервисах и кешах, показывая очень хороший прирост производительности по сравнению с блоками synchronized . По сути, класс работает в 2-х взаимоисключающих режимах: много reader’ов читают данные в параллель и когда только 1 writer пишет данные.
класс StampedLock :
StampedLock представлен в Java 8.
Пример ReentrantLock:
одна блокировка сразу на два метода .
public class ReentrantLockExample < public static void main(String[] args) throws InterruptedException < Resource resource = new Resource(6, 14); MyThread thread1 = new MyThread(resource); thread1.setName("firstThread"); MyThread thread2 = new MyThread(resource); thread1.start(); thread2.start(); thread1.join(); thread2.join(); System.out.println(resource.getI()); System.out.println(resource.getPhone()); >> class MyThread extends Thread < private final Resource resource; MyThread(Resource res) < resource = res; >@Override public void run() < resource.incrementI(); > > class Resource < private int i; public int getPhone() < return phone; >Resource(int i, int phone) < this.i = i; this.phone = phone; >private int phone; private final Lock lock = new ReentrantLock(); void incrementI() < lock.lock(); int iLocal = this.i; if (Thread.currentThread().getName().equals("firstThread")) < Thread.yield(); >iLocal++; this.i = iLocal; incrementPhone(); > void incrementPhone() < int phoneLocal = this.phone; if (Thread.currentThread().getName().equals("firstThread")) < Thread.yield(); >phoneLocal++; this.phone = phoneLocal; lock.unlock(); > int getI() < return i; >>
Пример Condition:
Блокировка с условием .
public class ConditionsExample < private static Lock lock = new ReentrantLock(); private static Condition condition = lock.newCondition(); private static int bankAccount =0; public static void main(String[] args) < new AccountMinusMoney().start(); new AccountPlusMoney().start(); >static class AccountPlusMoney extends Thread< @Override public void run() < lock.lock(); bankAccount +=10; System.out.println("\n ------ прибавили 10 руб. \n"); condition.signal(); lock.unlock(); > > static class AccountMinusMoney extends Thread < @Override public void run() < if(bankAccount 10)< try < lock.lock(); System.out.println("не можем списать деньги так как сумма на счету меньше 10 руб. =("); System.out.println(". ждём . другой поток . "); condition.await(); lock.unlock(); System.out.println(". другой поток отработал . продолжаем ! =) "); >catch (InterruptedException e) < e.printStackTrace(); >> bankAccount -=10; System.out.println("\n ------ отняли 10 руб.\n"); System.out.println(); > > >
Полезные ссылки:
- interface Lock JavaDoc (Java 8)
- interface Lock JavaDoc (Java 7)
- interface Condition JavaDoc (Java 8)
- interface Condition JavaDoc (Java 7)
- class ReentrantLock JavaDoc (Java 8)
- class ReentrantLock JavaDoc (Java 7)
- interface ReadWriteLock JavaDoc (Java 8)
- class ReentrantReadWriteLock JavaDoc (Java 8)
- class ReentrantReadWriteLock JavaDoc (Java 7)
- class StampedLock JavaDoc (Java 8)
- Guide to java.util.concurrent.Locks Baeldung
Pointer Lock API
Pointer lock API(прежнее название Mouse Lock API) обеспечивает методы ввода, основанные на движении мыши , а не только абсолютно позиционированых координатах курсора в окне. Это даёт вам доступ к необработанным движениям мыши, прикрепляет курсор мыши к любому элементу в окне браузера, предоставляет возможность вычислять координаты мыши не ограниченной областью окна проекции, и скрывает курсор из поля зрения. Это идеальное решение для 3D игр, например.
Более того, API полезно для любых приложений, которые используют данные мыши для управления движениями, вращения объектов и изменения записей. Например пользователь может управлять наклоном просто двигая мышь, не нажимая ни на какие кнопки. Сами кнопки освобождаются под другие задачи. Примерами могут послужить программы для просмотра карт или спутниковой съёмки.
Блокировка указателя позволяет вам получить доступ к данным мыши, даже если курсор ушёл за границы экрана или браузера. Например, ваши пользователи могут продолжать вращать или управлять 3D моделью движением мыши бесконечно. Без блокировки вращение или управление останавливается, как только курсор достигает края браузера или экрана. Геймеры теперь могут нажимать кнопки и водить курсором взад и вперёд, не боясь покинуть игровое поле и случайно переключится на другое приложение.
Основные концепции
Pointer lock is related to mouse capture. Mouse capture provides continued delivery of events to a target element while a mouse is being dragged, but it stops when the mouse button is released. Pointer lock is different from mouse capture in the following ways:
- It is persistent: Pointer lock does not release the mouse until an explicit API call is made or the user uses a specific release gesture.
- It is not limited by browser or screen boundaries.
- It continues to send events regardless of mouse button state.
- It hides the cursor.
Обзор методов/свойств
Этот раздел содержит краткое описание каждого свойства и метода, связанного со спецификацией блокировки указателя.
requestPointerLock()
The Pointer lock API, similar to the Fullscreen API (en-US) , extends DOM elements by adding a new method, requestPointerLock , which is vendor-prefixed for now. You would currently declare it something like this, for example if you wanted to request pointer lock on a canvas element.:
.requestPointerLock = canvas.requestPointerLock || canvas.mozRequestPointerLock || canvas.webkitRequestPointerLock; canvas.requestPointerLock();
pointerLockElement and exitPointerLock()
The Pointer lock API also extends the Document interface, adding both a new property and a new method. The new property is used for accessing the currently locked element (if any), and is named pointerLockElement (en-US), which is vendor-prefixed for now. The new method on Document is exitPointerLock (en-US) and, as the name implies, it is used to exit Pointer lock.
The pointerLockElement (en-US) property is useful for determining if any element is currently pointer locked (e.g., for doing a boolean check) and also for obtaining a reference to the locked element, if any.
Here is an example of using pointerLockElement :
if ( document.pointerLockElement === canvas || document.mozPointerLockElement === canvas || document.webkitPointerLockElement === canvas ) console.log("The pointer lock status is now locked"); > else console.log("The pointer lock status is now unlocked"); >
The Document.exitPointerLock (en-US) method is used to exit pointer lock, and like requestPointerLock , works asynchronously using the pointerlockchange (en-US) and pointerlockerror (en-US) events, which you’ll see more about below.
.exitPointerLock = document.exitPointerLock || document.mozExitPointerLock || document.webkitExitPointerLock; // Attempt to unlock document.exitPointerLock();
pointerlockchange event
When the Pointer lock state changes—for example, when calling requestPointerLock , exitPointerLock (en-US), the user pressing the ESC key, etc.—the pointerlockchange (en-US) event is dispatched to the document . This is a simple event and contains no extra data.
if ("onpointerlockchange" in document) document.addEventListener("pointerlockchange", lockChangeAlert, false); > else if ("onmozpointerlockchange" in document) document.addEventListener("mozpointerlockchange", lockChangeAlert, false); > else if ("onwebkitpointerlockchange" in document) document.addEventListener("webkitpointerlockchange", lockChangeAlert, false); > function lockChangeAlert() if ( document.pointerLockElement === canvas || document.mozPointerLockElement === canvas || document.webkitPointerLockElement === canvas ) console.log("The pointer lock status is now locked"); // Do something useful in response > else console.log("The pointer lock status is now unlocked"); // Do something useful in response > >
pointerlockerror event
When there is an error caused by calling requestPointerLock or exitPointerLock (en-US), the pointerlockerror (en-US) event is dispatched to the document . This is a simple event and contains no extra data.
.addEventListener("pointerlockerror", lockError, false); document.addEventListener("mozpointerlockerror", lockError, false); document.addEventListener("webkitpointerlockerror", lockError, false); function lockError(e) alert("Pointer lock failed"); >
Примечание: The above events are currently prefixed with moz in Firefox and webkit in Chrome.
Extensions to mouse events
The Pointer lock API extends the normal MouseEvent interface with movement attributes.
partial interface MouseEvent readonly attribute long movementX; readonly attribute long movementY; >;
Примечание: The movement attributes are currently prefixed as .mozMovementX and .mozMovementY in Firefox, and .webkitMovementX and .webkitMovementY in Chrome.
Two new parameters to mouse events— movementX (en-US) and movementY (en-US)—provide the change in mouse positions. The values of the parameters are the same as the difference between the values of MouseEvent properties, screenX and screenY (en-US), which are stored in two subsequent mousemove (en-US) events, eNow and ePrevious . In other words, the Pointer lock parameter movementX = eNow.screenX — ePrevious.screenX .
Locked state
When Pointer lock is enabled, the standard MouseEvent properties clientX , clientY , screenX , and screenY (en-US) are held constant, as if the mouse is not moving. The movementX (en-US) and movementY (en-US) properties continue to provide the mouse’s change in position. There is no limit to movementX (en-US) and movementY (en-US) values if the mouse is continuously moving in a single direction. The concept of the mouse cursor does not exist and the cursor cannot move off the window or be clamped by a screen edge.
Unlocked state
The parameters movementX (en-US) and movementY (en-US) are valid regardless of the mouse lock state, and are available even when unlocked for convenience.
When the mouse is unlocked, the system cursor can exit and re-enter the browser window. If that happens, movementX (en-US) and movementY (en-US) could be set to zero.
Simple example walkthrough
We’ve written a simple pointer lock demo to show you how to use it to set up a simple control system (see source code). The demo looks like this:

Set initial x and y positions on the canvas:
var x = 50; var y = 50;
The canvasDraw() function draws the ball in the current x and y positions, but it also includes if() statements to check whether the ball has gone off the edges of the canvas. If so, it makes the ball wrap around to the opposite edge.
function canvasDraw() if (x > canvas.clientWidth + 20) x = 0; > if (y > canvas.clientHeight + 20) y = 0; > if (x -20) x = canvas.clientWidth; > if (y -20) y = canvas.clientHeight; > ctx.fillStyle = "black"; ctx.fillRect(0, 0, canvas.clientWidth, canvas.clientHeight); ctx.fillStyle = "#f00"; ctx.beginPath(); ctx.arc(x, y, 20, 0, degToRad(360), true); ctx.fill(); >
The pointer lock methods are currently prefixed, so next we’ll fork them for the different browser implementations.
.requestPointerLock = canvas.requestPointerLock || canvas.mozRequestPointerLock || canvas.webkitRequestPointerLock; // pointer lock object forking for cross browser document.exitPointerLock = document.exitPointerLock || document.mozExitPointerLock || document.webkitExitPointerLock; //document.exitPointerLock();
Now we set up an event listener to run the requestPointerLock() method on the canvas when it is clicked, which initiates pointer lock.
.onclick = function () canvas.requestPointerLock(); >;
Now for the dedicated pointer lock event listener: pointerlockchange . When this occurs, we run a function called lockChangeAlert() to handle the change.
// pointer lock event listener // Hook pointer lock state change events for different browsers document.addEventListener("pointerlockchange", lockChangeAlert, false); document.addEventListener("mozpointerlockchange", lockChangeAlert, false); document.addEventListener("webkitpointerlockchange", lockChangeAlert, false);
This function checks the pointLockElement property to see if it is our canvas. If so, it attached an event listener to handle the mouse movements with the canvasLoop() function. If not, it removes the event listener again.
function lockChangeAlert() if ( document.pointerLockElement === canvas || document.mozPointerLockElement === canvas || document.webkitPointerLockElement === canvas ) console.log("The pointer lock status is now locked"); document.addEventListener("mousemove", canvasLoop, false); > else console.log("The pointer lock status is now unlocked"); document.removeEventListener("mousemove", canvasLoop, false); > >
A tracker is set up to write out the X and Y values to the screen, for reference.
var tracker = document.createElement("p"); var body = document.querySelector("body"); body.appendChild(tracker); tracker.style.position = "absolute"; tracker.style.top = "0"; tracker.style.right = "10px"; tracker.style.backgroundColor = "white";
The canvasLoop() function first forks the movementX and movementY properties, as they are also prefixed currently in some browsers. It then adds those property’s values to x and y, and reruns canvasDraw() with those new values so the ball position is updated. Finally, we use requestAnimationFrame() to run the loop again and again.
function canvasLoop(e)
iframe limitations
Pointer lock can only lock one iframe at a time. If you lock one iframe, you cannot try to lock another iframe and transfer the target to it; Pointer lock will error out. To avoid this limitation, first unlock the locked iframe, and then lock the other.
While iframes work by default, «sandboxed» iframes block Pointer lock. The ability to avoid this limitation, in the form of the attribute/value combination , is expected to appear in Chrome soon.
Specifications
| Specification |
|---|
| Pointer Lock 2.0 |
Совместимость с браузерами
api.Document.exitPointerLock
BCD tables only load in the browser
api.Element.requestPointerLock
BCD tables only load in the browser
See also
Found a content problem with this page?
- Edit the page on GitHub.
- Report the content issue.
- View the source on GitHub.
This page was last modified on 6 янв. 2024 г. by MDN contributors.
Your blueprint for a better internet.
MDN
Support
- Product help
- Report an issue
Our communities
Developers
- Web Technologies
- Learn Web Development
- MDN Plus
- Hacks Blog
- Website Privacy Notice
- Cookies
- Legal
- Community Participation Guidelines
Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2024 by individual mozilla.org contributors. Content available under a Creative Commons license.