All articles

Technical

Background Audio Playback in Android TWAs

September 10, 2026 · 6 min read

Many developers convert their web-based music players, podcast directories, radio stations, or meditation apps into Android applications using a Trusted Web Activity (TWA). However, a common technical obstacle is that audio playback frequently pauses the moment the user locks their device, switches to another application, or minimises the app. This issue stems from how mobile operating systems and mobile web browsers manage memory and power consumption.

By default, Android aggressively manages active applications to preserve battery life and hardware resources. When a TWA moves to the background, the underlying web rendering engine prioritises battery savings, which often results in the suspension of active JavaScript execution, network requests, and media contexts. To build a reliable background audio experience, you must utilise specific web APIs and configure your application to communicate its active state to the Android operating system.

The Browser Lifecycle and Background Audio

In a traditional desktop web browser, background tabs are occasionally throttled, but audio playback is generally allowed to persist without strict intervention. On mobile platforms, the rules are significantly more restrictive. A Trusted Web Activity runs inside a customized browser instance. When this instance is no longer visible on the screen, the Android operating system monitors its resource consumption closely.

If your web application attempts to play audio using standard HTML5 audio elements or the Web Audio API without declaring its background intentions, the operating system will treat the application as inactive. When resource limits are reached or the device enters a sleep state, the audio context is suspended, causing playback to freeze. To resolve this, you must explicitly declare to the browser, and consequently to the Android operating system, that your application is actively presenting media to the user.

Implementing the Media Session API

The Media Session API is the primary tool for managing background audio in a Trusted Web Activity. This API allows your web application to communicate directly with the Android system media player, establishing an active media state that persists even when the application is minimised or the screen is locked.

When you implement the Media Session API, your app registers metadata with the operating system, including the track title, artist name, album art, and active playback status. This actions tells Android that the application is playing meaningful media, which prevents the OS from suspending the underlying browser thread.

The following example demonstrates how to set up the Media Session metadata within your JavaScript application:

if ('mediaSession' in navigator) { navigator.mediaSession.metadata = new MediaMetadata({ title: 'Morning Meditation', artist: 'PWA Harmony', album: 'Mindfulness Series', artwork: [ { src: 'https://example.com/artwork-96.png', sizes: '96x96', type: 'image/png' }, { src: 'https://example.com/artwork-512.png', sizes: '512x512', type: 'image/png' } ] }); }

By registering this metadata, your application hooks into the native Android system. This ensures that the system lock screen displays your custom media playback card, and the notification drawer provides controls to pause, play, or skip tracks within your TWA.

Handling Audio Focus on Android

Android manages media playback across multiple applications through a mechanism known as Audio Focus. Only one application can hold audio focus at any given time. If a user is listening to music in your TWA app and receives a phone call, or plays a video on a social media platform, your app must react appropriately to losing focus.

If your application fails to manage audio focus transitions, the operating system will forcefully terminate your media session, or worse, play both audio streams simultaneously, creating a poor user experience. To handle these transitions, you must configure event listeners on the Media Session interface. This allows your app to listen for system-level playback commands, such as pause, play, and track navigation.

Here is how you can configure action handlers to respond to system commands:

navigator.mediaSession.setActionHandler('play', () => { audioDocumentElement.play(); navigator.mediaSession.playbackState = 'playing'; }); navigator.mediaSession.setActionHandler('pause', () => { audioDocumentElement.pause(); navigator.mediaSession.playbackState = 'paused'; }); navigator.mediaSession.setActionHandler('seekbackward', (details) => { const offset = details.seekOffset || 10; audioDocumentElement.currentTime = Math.max(audioDocumentElement.currentTime - offset, 0); }); navigator.mediaSession.setActionHandler('seekforward', (details) => { const offset = details.seekOffset || 10; audioDocumentElement.currentTime = Math.min(audioDocumentElement.currentTime + offset, audioDocumentElement.duration); });

By handling these actions, you ensure that physical hardware buttons (such as those on Bluetooth headphones) and native software controls on the Android lock screen can successfully control playback inside your converted PWA.

Managing the Service Worker and Background Actions

While the Media Session API keeps the audio thread alive, your application may also need to fetch new audio files or download additional media segments while running in the background. This is particularly important for streaming applications that buffer content dynamically.

To support background network operations, your Service Worker should be configured to handle asset caching and network requests efficiently. It is recommended to use pre-caching for smaller audio files or utilize the Background Fetch API for larger files like podcasts or complete audio albums. This prevents network timeouts from interrupting playback when the device changes cell towers or enters a low-connectivity zone while in the user's pocket.

Feature Support Comparison

To understand the structural difference between standard web playback and a fully integrated TWA background audio setup, refer to the comparison table below:

FeatureStandard Web AudioTWA with Media Session API
Screen Lock PlaybackSuspended quickly by OSContinuous uninterrupted playback
System Notification ControlsNot availableFully integrated with play/pause buttons
Lock Screen ArtworkGeneric browser iconCustom high-resolution album art
Hardware Button ControlUnreliable or ignoredFully supported (Bluetooth/Headphones)
Coexistence with Phone CallsFrequently fails to pausePauses immediately upon loss of focus

Optimising the User Experience

To ensure your background audio is never terminated prematurely, always follow these best practices:

  • Initialize your audio elements in response to a user action, such as a tap on a play button, to comply with browser autoplay restrictions.
  • Provide fallback offline audio files cached via your service worker to handle sudden network drops.
  • Keep the volume level of non-essential UI sound effects low so they do not interrupt the main background audio thread.
  • Verify that your Web App Manifest contains a valid theme colour, which the native Android system will use to style the background of your lock screen media card.

By implementing these programmatic standards, your converted PWA will behave indistinguishably from a native Android audio application, delivering a seamless experience for your users from the Google Play Store.

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