Table of Contents
While buying a phone, you must have come across its specifications about sensors. But, what are they actually? This blog talks in detail about sensors in Android devices and applications, their types, and examples.
Check out this video by Entri in Malayalam!
Introduction: What are Sensors in Android?
Most Android-powered devices have built-in sensors that measure motion, orientation, and various environmental conditions. These sensors are capable of providing raw data with high precision and accuracy, and are useful if you want to monitor three-dimensional device movement or positioning, or you want to monitor changes in the ambient environment near a device.
Source: Wikipedia
For example, a game might track readings from a device’s gravity sensor to infer complex user gestures and motions, such as tilt, shake, rotation, or swing. Likewise, a weather application might use a device’s temperature sensor and humidity sensor to calculate and report the dewpoint, or a travel application might use the geomagnetic field sensor and accelerometer to report a compass bearing.
The Android platform supports three broad categories of sensors:
- Motion sensors: These sensors measure acceleration forces and rotational forces along three axes. This category includes accelerometers, gravity sensors, gyroscopes, and rotational vector sensors.
- Environmental sensors: These sensors measure various environmental parameters, such as ambient air temperature and pressure, illumination, and humidity. This category includes barometers, photometers, and thermometers.
- Position sensors: These sensors measure the physical position of a device. This category includes orientation sensors and magnetometers.
You can access sensors available on the device and acquire raw sensor data by using the Android sensor framework. The sensor framework provides several classes and interfaces that help you perform a wide variety of sensor-related tasks. For example, you can use the sensor framework to do the following:
- Determine which sensors are available on a device.
- Determine an individual sensor’s capabilities, such as its maximum range, manufacturer, power requirements, and resolution.
- Acquire raw sensor data and define the minimum rate at which you acquire sensor data.
- Register and unregister sensor event listeners that monitor sensor changes.
Thinking about developing an app? Create one with Entri’s Flutter training course!
The Android Sensor Framework
The Android sensor framework lets you access many types of sensors. Some of these sensors are hardware-based and some are software-based. Hardware-based sensors are physical components built into a handset or tablet device. They derive their data by directly measuring specific environmental properties, such as acceleration, geomagnetic field strength, or angular change.
Software-based sensors are not physical devices, although they mimic hardware-based sensors. Software-based sensors derive their data from one or more of the hardware-based sensors and are sometimes called virtual sensors or synthetic sensors. The linear acceleration sensor and the gravity sensor are examples of software-based sensors.
Few Android-powered devices have every type of sensor. For example, most handset devices and tablets have an accelerometer and a magnetometer, but fewer devices have barometers or thermometers. Also, a device can have more than one sensor of a given type. For example, a device can have two gravity sensors, each one having a different range.
Sensor Framework Classes and Interfaces
You can access these sensors and acquire raw sensor data by using the Android sensor framework. The sensor framework is part of the android.hardware
package and includes the following classes and interfaces:
SensorManager
- You can use this class to create an instance of the sensor service. This class provides various methods for accessing and listing sensors, registering and unregistering sensor event listeners, and acquiring orientation information. This class also provides several sensor constants that are used to report sensor accuracy, set data acquisition rates, and calibrate sensors.
- You can get the instance of SensorManager by calling the method getSystemService() and passing the SENSOR_SERVICE constant in it.
Sensor
- You can use this class to create an instance of a specific sensor. This class provides various methods that let you determine a sensor’s capabilities.
SensorEvent
- The system uses this class to create a sensor event object, which provides information about a sensor event. A sensor event object includes the following information: the raw sensor data, the type of sensor that generated the event, the accuracy of the data, and the timestamp for the event.
SensorEventListener
- You can use this interface to create two call-back methods that receive notifications (sensor events) when sensor values change or when sensor accuracy changes.
-
Public and abstract methods Description void onAccuracyChanged(Sensor sensor, int accuracy) it is called when sensor accuracy is changed. void onSensorChanged(SensorEvent event) it is called when sensor values are changed.
In a typical application you use these sensor-related APIs to perform two basic tasks:
-
Identifying sensors and sensor capabilities:
Identifying sensors and sensor capabilities at runtime is useful if your application has features that rely on specific sensor types or capabilities. For example, you may want to identify all of the sensors that are present on a device and disable any application features that rely on sensors that are not present. Likewise, you may want to identify all of the sensors of a given type so you can choose the sensor implementation that has the optimum performance for your application.
-
Monitor sensor events:
Monitoring sensor events is how you acquire raw sensor data. A sensor event occurs every time a sensor detects a change in the parameters it is measuring. A sensor event provides you with four pieces of information: the name of the sensor that triggered the event, the timestamp for the event, the accuracy of the event, and the raw sensor data that triggered the event.
Become an Android App Developer with Entri’s Flutter training course! Join Now!
Sensor Availability
While sensor availability varies from device to device, it can also vary between Android versions. This is because the Android sensors have been introduced over the course of several platform releases. For example, many sensors were introduced in Android 1.5 (API Level 3), but some were not implemented and were not available for use until Android 2.3 (API Level 9).
Likewise, several sensors were introduced in Android 2.3 (API Level 9) and Android 4.0 (API Level 14). Two sensors have been deprecated and replaced by newer, better sensors. Only four platforms are listed because those are the platforms that involved sensor changes. Sensors that are listed as deprecated are still available on subsequent platforms (provided the sensor is present on a device), which is in line with Android’s forward compatibility policy.
Types of Sensors in Android
Below are the different types of sensors in Android.
Android supports three types of sensors:
1) Motion Sensors
These are used to measure acceleration forces and rotational forces along with three axes.
2) Position Sensors
These are used to measure the physical position of device.
3) Environmental Sensors
These are used to measure the environmental changes such as temperature, humidity etc.
Android Simple Sensor App Example
Let’s see the two sensor examples.
-
A sensor example that prints x, y and z axis values.
Input:
#include <Wire.h>
#include <MPU6050.h>
MPU6050 mpu;
void setup() {
Serial.begin(9600);
Wire.begin();
mpu.initialize();
if (!mpu.testConnection()) {
Serial.println("MPU6050 connection failed");
while (1);
}
Serial.println("MPU6050 connection successful");
}
void loop() {
int16_t ax, ay, az;
mpu.getAcceleration(&ax, &ay, &az);
Serial.print("X: "); Serial.print(ax);
Serial.print(" | Y: "); Serial.print(ay);
Serial.print(" | Z: "); Serial.println(az);
delay(500);
}
Output:
MPU6050 connection successful
X: 123 | Y: -245 | Z: 16234
X: 118 | Y: -248 | Z: 16240
X: 120 | Y: -250 | Z: 16236
X: 122 | Y: -247 | Z: 16232
X: 119 | Y: -249 | Z: 16238
-
A sensor example that changes the background color when device is shuffled.
Input:
#include <Wire.h>
#include <MPU6050.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
#define OLED_RESET -1
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
MPU6050 mpu;
bool inverted = false;
void setup() {
Serial.begin(9600);
Wire.begin();
// Initialize MPU6050
mpu.initialize();
if (!mpu.testConnection()) {
Serial.println("MPU6050 connection failed");
while (1);
}
Serial.println("MPU6050 connected");
// Initialize display
if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
Serial.println(F("SSD1306 allocation failed"));
while (1);
}
display.clearDisplay();
display.setTextSize(2);
display.setTextColor(SSD1306_WHITE);
display.setCursor(0, 0);
display.println("Ready");
display.display();
}
void loop() {
int16_t ax, ay, az;
mpu.getAcceleration(&ax, &ay, &az);
// Calculate total acceleration vector magnitude
float totalAccel = sqrt(ax * ax + ay * ay + az * az);
// Shake threshold - tune as needed (around 20000 is a strong shake)
if (totalAccel > 20000) {
inverted = !inverted; // toggle display inversion
display.invertDisplay(inverted);
display.clearDisplay();
display.setCursor(0, 0);
display.setTextSize(2);
display.setTextColor(SSD1306_WHITE);
display.println("Shaken!");
display.display();
delay(1000); // debounce
}
delay(100); // poll rate
}
Output:
Time | Event | Display Appearance |
---|---|---|
0s | Power on | “Ready” (black bg, white text) |
Shake #1 | Detected | “Shaken!” (white bg, black text) |
Shake #2 | Detected | “Shaken!” (black bg, white text) |
Shake #3 | Detected | “Shaken!” (white bg, black text) |
Conclusion
Android devices are equipped with a lot of sensors that gives it a chance to interact with the physical world. Android app developers can actually leverage the Android Sensor API to create innovative and precise-functioning applications. It is safe to say that understanding of these sensors, their types, and examples, is crucial to build applications that seamlessly enhance the user experience. You can literally thrive in the world of app development with these sensors as one of your assets. Happy coding!
Related articles |
|
Learning Android Development In 2025 | What Is An SDK in Android? (With Definition,Types And Benefits) |
Frequently Asked Questions
What are Android sensors?
Android sensors are hardware components embedded in Android devices that detect and measure physical properties such as motion, orientation, and environmental conditions.
How many types of sensors are there in Android?
Android devices typically support three main categories of sensors:
-
Motion Sensors: Accelerometer, Gyroscope, Gravity, Linear Acceleration, Rotation Vector.
-
Position Sensors: Orientation, Magnetic Field.
-
Environmental Sensors: Light, Pressure, Temperature, Humidity.
How can I access sensor data in an Android application?
You can access sensor data using the SensorManager
class to get instances of sensors and register listeners to receive sensor events. Implement the SensorEventListener
interface to handle sensor data changes.
What is the purpose of the SensorEventListener interface?
The SensorEventListener
interface provides callback methods (onSensorChanged()
and onAccuracyChanged()
) that allow your application to respond to changes in sensor data and sensor accuracy.
Can all Android devices support all types of sensors?
No, the availability of sensors varies by device. Not all Android devices are equipped with every sensor type. You can check the availability of a specific sensor using the SensorManager
‘s getSensorList()
method.
How can I ensure my application works across different devices with varying sensor capabilities?
To ensure compatibility, always check for the presence of a sensor before using it. Use the SensorManager
to query available sensors and implement fallback mechanisms or alternative functionalities if a sensor is not available on the device.