Table of Contents
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. 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.
This topic provides an overview of the sensors that are available on the Android platform. It also provides an introduction to the sensor framework.
Ace your coding skills with Entri !
Introduction to Sensors
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.
Ace your coding skills with Entri !
Sensor Framework
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.
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 callback methods that receive notifications (sensor events) when sensor values change or when sensor accuracy changes.
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.
Ace your coding skills with Entri !
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.
Ace your coding skills with Entri !
Sensors can be used to monitor the three-dimensional device movement or change in the environment of the device.
Android provides sensor api to work with different types of sensors.
Types of Sensors in Android
1: Which of the following data structures allows elements to be added and removed in a Last-In, First-Out (LIFO) order?
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.
Ace your coding skills with Entri !
Android Sensor API
Android sensor api provides many classes and interface. The important classes and interfaces of sensor api are as follows:
1) SensorManager class
The android.hardware.SensorManager class provides methods :
- to get sensor instance,
- to access and list sensors,
- to register and unregister sensor listeners etc.
You can get the instance of SensorManager by calling the method getSystemService() and passing the SENSOR_SERVICE constant in it.
- SensorManager sm = (SensorManager)getSystemService(SENSOR_SERVICE);
Ace your coding skills with Entri !
2) Sensor class
The android.hardware.Sensor class provides methods to get information of the sensor such as sensor name, sensor type, sensor resolution, sensor type etc.
3) SensorEvent class
Its instance is created by the system. It provides information about the sensor.
4) SensorEventListener interface
It provides two call back methods to get information when sensor values (x,y and z) change or 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. |
Ace your coding skills with Entri !
Android simple sensor app example
Let’s see the two sensor examples.
- A sensor example that prints x, y and z axis values. Here, we are going to see that.
- A sensor example that changes the background color when device is shuffled. Click for changing background color of activity sensor example
activity_main.xml
There is only one textview in this file.
- <RelativeLayout xmlns:androclass=“http://schemas.android.com/apk/res/android”
- xmlns:tools=“http://schemas.android.com/tools”
- android:layout_width=“match_parent”
- android:layout_height=“match_parent”
- tools:context=“.MainActivity” >
- <TextView
- android:id=“@+id/textView1”
- android:layout_width=“wrap_content”
- android:layout_height=“wrap_content”
- android:layout_alignParentLeft=“true”
- android:layout_alignParentTop=“true”
- android:layout_marginLeft=“92dp”
- android:layout_marginTop=“114dp”
- android:text=“TextView” />
- </RelativeLayout>
Activity class
Let’s write the code that prints values of x axis, y axis and z axis.
- package com.example.sensorsimple;
- import android.app.Activity;
- import android.os.Bundle;
- import android.widget.TextView;
- import android.widget.Toast;
- import android.hardware.SensorManager;
- import android.hardware.SensorEventListener;
- import android.hardware.SensorEvent;
- import android.hardware.Sensor;
- import java.util.List;
- public class MainActivity extends Activity {
- SensorManager sm = null;
- TextView textView1 = null;
- List list;
- SensorEventListener sel = new SensorEventListener(){
- public void onAccuracyChanged(Sensor sensor, int accuracy) {}
- public void onSensorChanged(SensorEvent event) {
- float[] values = event.values;
- textView1.setText(“x: “+values[0]+“\ny: “+values[1]+“\nz: “+values[2]);
- }
- };
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- /* Get a SensorManager instance */
- sm = (SensorManager)getSystemService(SENSOR_SERVICE);
- textView1 = (TextView)findViewById(R.id.textView1);
- list = sm.getSensorList(Sensor.TYPE_ACCELEROMETER);
- if(list.size()>0){
- sm.registerListener(sel, (Sensor) list.get(0), SensorManager.SENSOR_DELAY_NORMAL);
- }else{
- Toast.makeText(getBaseContext(), “Error: No Accelerometer.”, Toast.LENGTH_LONG).show();
- }
- }
- @Override
- protected void onStop() {
- if(list.size()>0){
- sm.unregisterListener(sel);
- }
- super.onStop();
- }
- }
Output: