All articles

Tutorial

Implementing Screen Wake Lock in Android TWAs

September 8, 2026 · 7 min read

For many categories of applications, preventing the device's display from dimming or turning off automatically is a core requirement. Utility apps such as cooking recipe books, turn-by-turn navigation guides, workout timers, presentation tools, and dashboard monitors must keep the screen illuminated while the user interacts with the app passively. In a native Android application, developers achieve this by programmatically adding the FLAG_KEEP_SCREEN_ON flag to their activity window. For web developers deploying their applications using a Trusted Web Activity (TWA), you can manage this directly from your JavaScript codebase using the modern W3C Screen Wake Lock API.

How the Screen Wake Lock API Functions in a TWA

The Screen Wake Lock API provides a standard web-native interface to request that the host operating system keep the screen active. Because a TWA is powered directly by the system's underlying Chromium engine (such as Google Chrome), the API functions with full compatibility. When your PWA requests a wake lock, the browser engine translates this request into native Android system calls, instructing the OS to hold a CPU wake lock on behalf of the application.

This process is highly secure and does not require manual permission declarations inside your AndroidManifest.xml. The permission is implicitly granted because the application runs in a secure, verified context linked directly to your digital asset links.

Step-by-Step JavaScript Implementation

The Screen Wake Lock API is designed to be developer-friendly but requires explicit defensive programming to handle environment changes, user actions, and hardware constraints. Below is the standard structure for implementing a robust screen wake lock module in your PWA.

1. Feature Detection

Before executing any wake lock commands, verify that the user's browser engine supports the API. This prevents errors on older devices or alternative system browsers:

if ('wakeLock' in navigator) {
  // The Screen Wake Lock API is supported
} else {
  // Fallback behavior or user notification
}

2. Requesting the Wake Lock

To request a wake lock, call the navigator.wakeLock.request() method and pass the argument 'screen'. This operation is asynchronous and returns a promise containing a WakeLockSentinel object:

let wakeLockSentinel = null;

async function requestWakeLock() {
  try {
    wakeLockSentinel = await navigator.wakeLock.request('screen');
    console.log('Screen Wake Lock is active.');
  } catch (err) {
    console.error('Failed to acquire wake lock:', err.message);
  }
}

The system can reject this promise under several scenarios. For instance, if the device is in extreme battery saver mode, or if the document is not active or visible, the request will fail. Your application must handle these exceptions gracefully without crashing.

3. Releasing the Wake Lock

To prevent unnecessary battery consumption, release the wake lock as soon as the critical task is completed or the user navigates away from the active screen:

function releaseWakeLock() {
  if (wakeLockSentinel !== null) {
    wakeLockSentinel.release()
      .then(() => {
        wakeLockSentinel = null;
        console.log('Screen Wake Lock released.');
      });
  }
}

Managing the Wake Lock Lifecycle and Tab Visibility

A critical rule of the Screen Wake Lock API is that the browser automatically releases the lock if the application loses focus, is minimized, or the screen is turned off manually by the user. If the user navigates back to your TWA from another application or unlocks their device, your active wake lock will not be automatically restored by default.

To ensure that the screen remains active when the user returns to your application, you must monitor the page visibility state using the Page Visibility API and re-acquire the lock programmatically when the app becomes visible again:

const handleVisibilityChange = async () => {
  if (wakeLockSentinel !== null && document.visibilityState === 'visible') {
    await requestWakeLock();
  }
};

document.addEventListener('visibilitychange', handleVisibilityChange);

Battery Conservation and Best Practices

While holding a wake lock is highly convenient for specific use cases, holding it indefinitely degrades battery performance and can lead to poor reviews on the Google Play Store. To maintain optimal app performance and device health, observe the following best practices:

  • Implement a Timeout: Never leave a wake lock active indefinitely. If your app detects no user interaction for a predefined duration (e.g., 30 minutes), release the lock and allow the system default screen-saver settings to take over.
  • Add a UI Toggle: Provide an explicit control interface (such as a settings checkbox or a toggle switch) allowing users to manually enable or disable the "Keep screen active" feature.
  • Listen to the Release Event: The WakeLockSentinel object exposes an onrelease event handler. Monitor this to update your interface state so the user knows whether the lock is currently active.

Below is a summary of how system states impact your wake lock inside a TWA:

System EventWake Lock BehaviorRequired Application Action
User minimizes TWAAutomatically released by browser.Listen to visibility change, re-request on return.
Battery level drops lowMay be rejected or cancelled by Android OS.Catch rejection promise, notify user if appropriate.
Screen turned off manuallyAutomatically released.Wait for visibility change upon next unlock.

Verifying Wake Lock Behavior in Your App

To verify that your Screen Wake Lock is operating correctly before publishing your TWA build to Google Play, you can utilize the Chrome DevTools remote debugging interface. Connect your Android testing device via USB and navigate to the inspection console:

  • Open the Application panel in DevTools.
  • Locate the Sensors tab.
  • Trigger the wake lock within your app and observe if the active sentinel state transitions to active.
  • Manually lock and unlock the phone to ensure your visibility state event listeners correctly re-acquire the lock without throwing unhandled exceptions.

By incorporating the Screen Wake Lock API into your PWA codebase, you ensure that your TWA application provides a seamless, uninterrupted utility experience on Android devices without requiring heavy, complex native plugins.

Ready to ship your Android app?

Paste your PWA URL, get a signed APK and a Google Play ready AAB in minutes.

Build my app