Introduction
The Sensors Hardware Abstraction Layer (HAL) connects the Android framework's SensorService to the physical sensors on the device, such as the accelerometer, gyroscope, magnetometer, and ambient light sensor. Given that sensors are constantly polling data, the HAL is heavily optimized for low power consumption and batching.
Sensors HAL 2.0 and 2.1
Historically, the Sensors HAL used standard IPC to deliver every single sensor event. Starting with HAL 2.0 (and refined in 2.1), the architecture shifted to use Fast Message Queues (FMQ).
Instead of making a Binder call for every step taken or every degree of rotation, the vendor HAL writes sensor events directly into an FMQ. The framework periodically wakes up and drains the queue, drastically reducing IPC overhead and CPU wakeups.
// Polling for sensor events via FMQ in the framework
mEventQueue->read(events, numEventsToRead);
Sensor Types and Reporting Modes
Sensors in Android are categorized by their reporting modes, which dictate how the HAL handles their data:
- Continuous: Generates events at a constant rate (e.g., Gyroscope).
- On-change: Only generates an event when the value changes (e.g., Proximity sensor, Step Counter).
- One-shot: Generates a single event and then automatically disables itself (e.g., Significant Motion).
- Special: Features like the Step Detector or custom vendor sensors (Heart Rate).
The HAL implements a batch() function, allowing the framework to request that the hardware buffer continuous events in a hardware FIFO for several seconds before waking the main CPU to deliver them.
Dynamic Sensors
Standard sensors are soldered to the motherboard and declared statically at boot. However, Android also supports "Dynamic Sensors" - sensors that are attached and detached at runtime, such as a gamepad with a built-in accelerometer connected via Bluetooth or USB.
The Sensors HAL provides an onDynamicSensorsConnected callback mechanism. When a USB driver detects a new input device with a sensor, it registers it dynamically. The HAL then notifies SensorService, which exposes the new sensor to running Android applications.
Sensor HAL Test with sensors-unit-tests
Vendor implementations must pass strict compliance testing. The AOSP source tree includes native binaries like sensors-unit-tests and VTS modules (VtsHalSensorsV2_0TargetTest).
These tests verify that the HAL respects batching timeouts, correctly implements the flush() command (which forces the hardware FIFO to empty immediately), and ensures that sensor timestamps are strictly monotonic and aligned with the system CLOCK_BOOTTIME.