Javatpoint Logo
Javatpoint Logo

Android Sensor Tutorial

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.

android sensor

Types of Sensors

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 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.

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 methodsDescription
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.

Android simple sensor app example

Let's see the two sensor examples.

  1. A sensor example that prints x, y and z axis values. Here, we are going to see that.
  2. A sensor example that changes the background color when device is shuffled. Click for changing background color of activity sensor example


There is only one textview in this file.

File: activity_main.xml

Activity class

Let's write the code that prints values of x axis, y axis and z axis.



android sensor example output 1

What is next?

Click for changing background color of activity sensor example

Youtube For Videos Join Our Youtube Channel: Join Now


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Trending Technologies

B.Tech / MCA