Access smartphone sensors through Web APIs including Generic Sensor API, Geolocation API, and DeviceOrientation API for browser-based sensing applications
Build cross-platform mobile sensor applications using React Native with access to accelerometers, gyroscopes, magnetometers, and GPS
Implement Progressive Web Apps (PWAs) with offline support and service workers for IoT data collection
Compare Web API limitations versus native mobile API capabilities for background sensing, sampling rates, and hardware access
In 60 Seconds
Modern web browsers provide standardized APIs (Generic Sensor API, Geolocation API, DeviceOrientation) that let you access smartphone accelerometers, GPS, gyroscopes, and microphones directly from JavaScript – no native app required. For deeper access, native frameworks like React Native offer cross-platform sensor integration.
Key Concepts
Web Sensor API: A browser-based JavaScript API providing access to device sensors (Geolocation, DeviceMotion, DeviceOrientation, AmbientLightSensor, Proximity) without native app installation; available in Chrome and some mobile browsers
DeviceMotionEvent: A JavaScript event providing accelerometer and gyroscope data (accelerationIncludingGravity, rotationRate) with update intervals configurable through event listener options; requires HTTPS and user permission
Geolocation API: Browser API returning GPS/Wi-Fi/cell-tower position (latitude, longitude, altitude, accuracy) via navigator.geolocation.getCurrentPosition() and watchPosition() for continuous tracking
Web Bluetooth API: Allows web applications to communicate with BLE peripherals directly from a browser using the GATT profile; enables web-based sensor dashboards to connect to custom BLE sensor hardware without native apps
Service Worker / PWA: A Progressive Web App with service worker caches sensor API callbacks offline; enables smartphone sensor data collection even without internet connectivity, syncing data when connectivity is restored
Android SensorManager API: Native Android Java/Kotlin API providing access to all hardware sensors with configurable sampling rates (SENSOR_DELAY_FASTEST to SENSOR_DELAY_UI); required for high-frequency accelerometer data (>50 Hz) not available through Web APIs
iOS CoreMotion Framework: Apple’s native framework for iPhone/iPad motion sensor access; provides CMMotionManager for accelerometer, gyroscope, and magnetometer at up to 100 Hz; no web API equivalent for high-frequency access
Sensor Permission Model: Modern mobile OS and browsers require explicit user permission for each sensor type; permissions must be requested in response to a user gesture (button tap), not on page load; denied permissions cannot be re-requested programmatically
For Beginners: Mobile Sensor APIs
An API (Application Programming Interface) is like a menu at a restaurant – it lists what you can order (request) and what you will get back. Mobile sensor APIs let your web page or app request data from the phone’s built-in sensors, like the accelerometer or GPS, using just a few lines of JavaScript. This means you can build sensor-based applications that run in a web browser without needing to create a native phone app.
15.2 Web-Based Mobile Sensing
15.2.1 Generic Sensor API (Web Standards)
Modern web browsers provide standardized APIs for accessing smartphone sensors without requiring native apps.
Battery impact: ~5% battery per hour with 50 Hz sampling
False positives: Phone in pocket/bag can trigger false steps from vehicle vibrations (add gyroscope to filter rotation-only events)
Putting Numbers to It
The Nyquist theorem determines the minimum sampling rate needed to accurately capture periodic motion like walking.
\(f_{sample} \geq 2 \times f_{max}\)
Show code
viewof max_frequency = Inputs.range([0.5,10], {value:2,step:0.1,label:"Maximum Signal Frequency (Hz)"})viewof actual_sample_rate = Inputs.range([1,100], {value:50,step:1,label:"Actual Sampling Rate (Hz)"})nyquist_min = max_frequency *2oversampling_factor = nyquist_min >0? actual_sample_rate / nyquist_min :0is_sufficient = actual_sample_rate >= nyquist_minhtml`<div style="background: #f8f9fa; padding: 20px; border-radius: 8px; font-family: Arial, sans-serif; margin-top: 20px;"> <h4 style="color: #2C3E50; margin-top: 0;">Nyquist Sampling Calculator</h4> <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px; margin-top: 15px;"> <div style="background: white; padding: 15px; border-radius: 6px; border-left: 4px solid #2C3E50;"> <div style="color: #7F8C8D; font-size: 12px; margin-bottom: 5px;">MAX FREQUENCY</div> <div style="color: #2C3E50; font-size: 24px; font-weight: bold;">${max_frequency.toFixed(1)} Hz</div> </div> <div style="background: white; padding: 15px; border-radius: 6px; border-left: 4px solid #16A085;"> <div style="color: #7F8C8D; font-size: 12px; margin-bottom: 5px;">NYQUIST MINIMUM</div> <div style="color: #2C3E50; font-size: 24px; font-weight: bold;">${nyquist_min.toFixed(1)} Hz</div> <div style="color: #7F8C8D; font-size: 11px;">= 2 × ${max_frequency.toFixed(1)} Hz</div> </div> <div style="background: white; padding: 15px; border-radius: 6px; border-left: 4px solid ${is_sufficient ?'#16A085':'#E74C3C'};"> <div style="color: #7F8C8D; font-size: 12px; margin-bottom: 5px;">STATUS</div> <div style="color: ${is_sufficient ?'#16A085':'#E74C3C'}; font-size: 18px; font-weight: bold;">${is_sufficient ?'✓ SUFFICIENT':'✗ ALIASING'} </div> <div style="color: #7F8C8D; font-size: 11px;">${oversampling_factor.toFixed(1)}× oversampling</div> </div> </div> <div style="margin-top: 15px; padding: 10px; background: ${is_sufficient ?'#d4edda':'#f8d7da'}; border-radius: 4px; font-size: 13px; color: ${is_sufficient ?'#155724':'#721c24'};">${is_sufficient ?`<strong>✓ No Aliasing:</strong> Sampling at ${actual_sample_rate} Hz exceeds the Nyquist minimum of ${nyquist_min.toFixed(1)} Hz by ${oversampling_factor.toFixed(1)}×. Signal will be accurately captured.`:`<strong>✗ Aliasing Risk:</strong> Sampling at ${actual_sample_rate} Hz is below the Nyquist minimum of ${nyquist_min.toFixed(1)} Hz. The signal will alias and appear at a lower frequency.`} </div></div>`
Worked example: Human walking has a typical step frequency of 2 Hz (120 steps/min). To reliably detect each step: - Maximum signal frequency: \(f_{max} = 2\) Hz - Minimum sampling rate (Nyquist): \(f_{sample} = 2 \times 2 = 4\) Hz - Practical sampling rate: 50 Hz (12.5× oversampling for noise immunity and peak detection accuracy)
If you sample at only 3 Hz (below Nyquist), the 2 Hz walking signal aliases to appear as 1 Hz, causing the step counter to miss every other step. The 50 Hz choice provides a 12.5× oversampling margin, enabling accurate peak detection even with signal noise and irregular gait patterns.
Why this approach works: Human walking has characteristic frequency (~2 Hz = 120 steps/min) and amplitude (magnitude peaks 10-12 m/s²). By detecting peaks above a threshold with minimum interval enforcement, we reliably count steps without complex ML models.
Limitations: Misses steps when phone is not on body (on desk), overcounts during driving on bumpy roads, undercounts during very slow walking (<0.5 m/s). Production apps combine accelerometer with gyroscope and GPS to improve accuracy.
For Kids: Meet the Sensor Squad!
Sammy the Sensor had a big question. “I know I live inside a phone, but how do apps actually talk to me?”
Max the Microcontroller explained: “There are two ways! The first is called a Web API – it is like opening a window in your web browser. Any website can peek through the window and ask, ‘Hey Sammy, how fast is the phone moving?’ No app download needed!”
“That sounds easy!” said Lila the LED.
“It is! But the window is small,” Max continued. “Websites can only peek at sensors for a little while, and only when the screen is on. For the full experience, you need a Native App – that is like giving the app its own key to the house. It can check on Sammy anytime, even in the background!”
Bella the Battery sighed. “But native apps that check sensors all the time use up a LOT of my energy!”
“That is the tradeoff,” Sammy nodded. “Web APIs are quick and easy but limited. Native apps are powerful but need more battery and a download from the app store.”
Max summarized: “Use the web window for quick experiments. Use the native key for serious projects!”
The Sensor Squad Lesson: Web APIs are like windows that let websites peek at phone sensors easily. Native APIs are like house keys that give apps full access. Each has its place – pick the right one for your project!
15.4 Knowledge Checks
Question 1: Web API Selection
You want to build a browser-based compass app that shows which direction the phone is pointing. Which Web API should you use?
Generic Sensor API (Accelerometer)
Geolocation API
DeviceOrientation API
Web Audio API
Answer
C) DeviceOrientation API. The DeviceOrientation API provides the alpha property (Z-axis rotation, 0-360 degrees), which corresponds to compass heading. It combines data from the magnetometer and gyroscope to determine which direction the device is facing. The Accelerometer only measures linear acceleration, GPS provides location but not heading when stationary, and Web Audio processes sound.
Question 2: Web vs Native APIs
What is the main limitation of using Web APIs for sensor access compared to native mobile APIs?
Web APIs cannot access accelerometers
Web APIs require HTTPS and have limited background execution
Web APIs only work on Android devices
Web APIs have no user permission model
Answer
B) Web APIs require HTTPS and have limited background execution. Web-based sensor access mandates a secure HTTPS connection, and browsers restrict background sensor access to conserve battery and protect privacy. Native APIs (Android SensorManager, iOS CoreMotion) allow continuous background sensing and offer higher sampling rates. However, Web APIs work across platforms and require no app installation, making them excellent for prototyping and short-duration data collection.
Key Takeaway
Web APIs offer the fastest path from idea to working sensor app – zero installation, cross-platform, and instant updates. Use them for prototypes, short-term data collection, and PWAs. Switch to native APIs (React Native, Android/iOS SDKs) when you need background sensing, higher sampling rates, or deeper hardware access.
Quiz: Mobile Sensor APIs
Interactive Quiz: Match Mobile Sensor APIs Concepts
Interactive Quiz: Sequence the Steps
Common Pitfalls
1. Assuming Web Sensor API Availability Across All Browsers
The Generic Sensor API and DeviceMotion API have inconsistent support — Safari on iOS requires iOS 13+ for DeviceMotion and does not support the Generic Sensor API; Chrome on Android requires HTTPS. Always check MDN compatibility tables for your target browser/OS combination before relying on specific web sensor APIs.
2. Not Handling Permission Denial Gracefully
Users who deny sensor permissions in browser prompts cannot be re-prompted by the application. If the user denies access, the application must detect this, display a clear explanation, and provide fallback behavior or manual input options — not silently fail or show an error message that forces app restart.
3. Ignoring Battery Impact of Continuous High-Rate Sensor Access
Requesting accelerometer data at SENSOR_DELAY_FASTEST (200 Hz) or keeping Geolocation watchPosition active continuously drains smartphone battery significantly — up to 20-30% per hour for GPS. Implement duty cycling (sample for 10 seconds, pause for 50 seconds) and use SENSOR_DELAY_NORMAL for most use cases.
4. Treating Web API Timestamps as High-Precision
DeviceMotionEvent timestamps come from the browser’s performance.now() timer, not a hardware clock synchronized to network time. Timestamps may have ±5-100 ms jitter compared to actual event times depending on browser, OS scheduling, and device load. For applications requiring precise event timing, use native APIs with hardware-timestamped sensor events.
Label the Diagram
15.5 What’s Next
If you want to…
Read this
Understand what hardware sensors mobile phones contain