All articles

Technical

Using Device Orientation and Motion APIs in Android TWAs

September 25, 2026 · 7 min read

Understanding Device Sensors in Trusted Web Activities

When developers convert immersive web applications into Android apps using a Trusted Web Activity (TWA), accessing native hardware capabilities is often a primary requirement. While classic WebView wrappers struggle with performance and permission delegation, TWAs run on top of the system's default browser engine, typically Google Chrome. This architecture grants web apps near-native access to hardware sensors, including the physical accelerometer, gyroscope, and magnetometer, directly through standard W3C Web APIs.

Using the Device Orientation and Device Motion APIs, you can build responsive interfaces, physics-based games, fitness tracking systems, or interactive mapping tools. However, executing these APIs inside an installed Android TWA application introduces specific requirements regarding security contexts, user permissions, OS-level battery optimisation, and sensor calibration. Understanding these technical layers ensures that your converted app provides a fluid experience indistinguishable from a native Java or Kotlin application.

Device Orientation vs Device Motion: What is the Difference?

To implement sensor-based features, you must understand the distinction between the two core events provided by the web platform. Although both APIs deal with spatial movement, they consume data from different physical micro-electromechanical systems (MEMS) chips on the Android device.

Event TypePhysical Sensor UsedPrimary Data PointsTypical Use Cases
DeviceOrientationEventGyroscope, MagnetometerAlpha, Beta, Gamma (degrees of rotation)Compass, 360-degree photo viewers, camera control
DeviceMotionEventAccelerometer, GyroscopeAcceleration (with/without gravity), rotation rateStep counting, shake-to-refresh gestures, motion detection

The DeviceOrientationEvent measures the physical rotation of the device relative to an Earth-based coordinate system. The DeviceMotionEvent, on the other hand, measures the rate of change in velocity over time across three dimensional axes (X, Y, and Z), as well as the rate of rotation.

How to Implement Device Orientation in a TWA

To access rotational data, you must register a listener on the window object for the deviceorientation event. The callback function receives an object containing three properties: alpha, beta, and gamma. These values represent the physical orientation of the device in degrees.

The alpha value represents rotation around the Z-axis, ranging from 0 to 360 degrees. This corresponds to the direction the top of the device is pointing relative to the magnetic North Pole. The beta value represents rotation around the X-axis, ranging from -180 to 180 degrees, indicating how much the device is tilted front-to-back. The gamma value represents rotation around the Y-axis, ranging from -90 to 90 degrees, indicating left-to-right tilt.

To capture these values, implement the following pattern in your application's JavaScript layer:

window.addEventListener('deviceorientation', (event) => {
const alpha = event.alpha;
const beta = event.beta;
const gamma = event.gamma;
if (alpha !== null) {
updateOrientationUI(alpha, beta, gamma);
}
});

Handling Absolute Orientation

In applications such as mapping and compass interfaces, absolute geographic alignment is essential. Standard deviceorientation events may use an arbitrary coordinate system depending on the device hardware and browser configuration. To guarantee alignment with magnetic North, you must target the deviceorientationabsolute event instead.

window.addEventListener('deviceorientationabsolute', (event) => {
const heading = event.alpha;
updateCompassDirection(heading);
});

Using deviceorientationabsolute ensures that Chrome utilizes both the gyroscope and the physical magnetometer to calculate a reliable bearing. If the hardware lacks a magnetometer, the absolute event will fall back to the relative event or return null values, which your code should handle gracefully.

Accessing the Accelerometer with Device Motion

To measure rapid physical movements, such as a shake gesture or steps walked, use the devicemotion event. This event updates at a high frequency, providing real-time vector components of acceleration and rotation.

The event callback contains three key properties: acceleration, which excludes gravity; accelerationIncludingGravity, which measures the steady 9.8 m/s² pull of the Earth along with physical movement; and rotationRate, which measures angular velocity in degrees per second.

window.addEventListener('devicemotion', (event) => {
const accX = event.acceleration.x;
const accY = event.acceleration.y;
const accZ = event.acceleration.z;
const interval = event.interval;
detectShakeGesture(accX, accY, accZ);
});

The interval property is critical for physics integrations; it states the exact time interval in milliseconds at which data is obtained from the hardware, allowing for precise double-integration calculations to estimate spatial displacement.

Managing Android Permissions and Security Requirements

Because physical sensors can theoretically be exploited for device fingerprinting, modern Chromium versions enforce strict security constraints on sensor access inside TWAs. To ensure your sensor integration works seamlessly once published to Google Play, you must satisfy three key pillars.

First, sensor access is strictly restricted to secure contexts. Your progressive web app must be served over HTTPS. During local testing, localhost is treated as secure, but any production environment must utilize a valid SSL certificate.

Second, you must ensure that your TWA's Digital Asset Links are configured correctly. If your asset links are broken or unverified, the TWA will display the URL address bar, and Android may demote the security origin of the web view, blocking direct hardware sensor reads. Correct implementation of the assetlinks.json file on your web server ensures that Chrome recognizes the app as trusted and clears security hurdles.

Third, you must implement user gesture requirements. Sensor listeners often cannot be registered on page load without prior user interaction. To prevent browser-level blocks, delay your sensor activation until the user clicks a button, starts a level, or interacts with the interface.

Best Practices for Sensor Performance and Battery Life

Physical sensors run at high sampling rates, frequently exceeding 60Hz. If your TWA handles complex DOM rendering or WebGL operations on every sensor event, you will quickly cause frame rate drops, UI lag, and excessive battery drain. To maintain a smooth 60fps or 120fps performance profile inside your TWA app, follow these architectural best practices:

  • Throttle calculations: Do not update the DOM directly inside the event listener. Instead, cache the sensor coordinates in local variables and use requestAnimationFrame to update the UI on the next screen refresh.
  • Unregister listeners: Always disconnect orientation and motion listeners when they are not actively required by the active viewport. Leaving sensor listeners running in the background will keep the device's hardware chipsets powered up, draining the user's battery.
  • Provide fallback options: Budget Android devices occasionally lack gyroscopes or accelerometers. Detect if properties are null or if the events fail to fire, and present alternative touch-based or on-screen joystick controls to your users.

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