Android Sensors with Examples

Generally, most of the android devices have built-in sensors to measure motion, orientation, and various environmental conditions. These sensors will provide raw data with high accuracy and are useful to monitor three-dimensional device movement or positioning or monitor changes in the ambient environment near a device.

 

For example, to report changes in the environment a weather application might use a temperature sensor and humidity sensor or a travel application might use the geomagnetic field sensor and accelerometer to report a compass bearing, etc.

 

The android mainly supports three categories of sensors those are,

 

CategoryDescription
Motion Sensors These sensors are useful to measure acceleration forces and rotational forces along three axes. This category includes accelerometers, gravity sensors, gyroscopes, and rotational vector sensors.
Environmental Sensors These sensors are useful to 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 are useful to measure the physical position of a device. This category includes orientation sensors and magnetometers.

Android provided a framework called sensor framework to access all the sensors available on device and to get all the raw sensor data. The sensor framework provided a wide variety of sensor-related tasks. For example, by using a sensor framework we can perform the following things

 

  • It lists all the available sensors on the device
  • It determines the capabilities of each sensor, such as its maximum range, manufacturer, power requirements, and resolution.
  • It can 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.

The Android sensor framework will allow us to access many types of sensors, some of these sensors are hardware-based and some are software-based. The Hardware-based sensors are physical components built on the handset or tablet device and Software-based sensors are not physical devices but they mimic Hardware-based sensors.

 

The Android sensor framework provided the following classes and interfaces to access device sensors and acquire raw sensor data.

 

ClassDescription
SensorManager By using this class we can create an instance of sensor service and this class provides a various methods for accessing and listing sensors, registering and unregistering sensor event listeners and acquiring orientation information.
Sensor By using this class we can create an instance of a specific sensor and this class provides various methods that let you determine the sensor's capabilities.
SensorEvent The system uses this class to create a sensor event object and it provides the raw sensor data, type of sensor that generated the event, accuracy of the data, and the timestamp for the event.
SensorEventListener We can use this interface to create two callback methods that receive notifications (sensor events) when sensor values change or when sensor accuracy changes.

Identify the List of Available Sensors

Following is the code snippet of identifying and listing all the available sensors on a device, checking whether the specific type of sensor exists or not and monitoring a sensor event changes using android sensor framework classes in android applications.

 

public class MainActivity extends AppCompatActivity implements SensorEventListener {
   
private SensorManager mgr;
   
private Sensor sensor;
   
@Override
   
protected void onCreate(Bundle savedInstanceState) {
       
super.onCreate(savedInstanceState);
        setContentView(R.layout.
activity_main);
       
mgr = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
       
sensor = mgr.getDefaultSensor(Sensor.TYPE_LIGHT);
        List<Sensor> deviceSensors =
mgr.getSensorList(Sensor.TYPE_ALL);
    }
   
@Override
   
public final void onAccuracyChanged(Sensor sensor, int accuracy) {
       
// Do something here if sensor accuracy changes.
   
}
   
@Override
   
public final void onSensorChanged(SensorEvent event) {
       
// Do something with this sensor value.
   
}
   
@Override
   
protected void onResume() {
       
super.onResume();
       
mgr.registerListener(this, sensor, SensorManager.SENSOR_DELAY_NORMAL);
    }
}

If you observe above code snippet, we used android sensor framework classes to list all available sensors on a device and monitoring the sensor event changes based on our requirements.

 

Now we will see how to use android sensor framework to get the list of available sensors on android device with examples.

Android Sensors Example

Following is the example of identifying the sensors and list all the available sensors on a device using android sensor framework.

 

Create a new android application using android studio and give names as SensorExample. In case if you are not aware of creating an app in android studio check this article Android Hello World App.

 

Once we create an application, open activity_main.xml file from \res\layout folder path and write the code like as shown below.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="10dp"
android:paddingRight="10dp">
<
TextView
   
android:id="@+id/sensorslist"
   
android:layout_width="wrap_content"
   
android:layout_height="wrap_content"
   
android:layout_marginTop="80dp"
   
android:text="Sensors"
   
android:textSize="20dp"
   
android:textStyle="bold"
   
android:layout_gravity="center"
   
android:visibility="gone"/>
</
LinearLayout>

Now open your main activity file MainActivity.java from \java\com.tutlane.sensorsexample path and write the code like as shown below

MainActivity.java

package com.tutlane.sensorsexample;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import java.util.List;

public class MainActivity extends AppCompatActivity {
   
private SensorManager mgr;
   
private TextView txtList;
   
@Override
   
protected void onCreate(Bundle savedInstanceState) {
       
super.onCreate(savedInstanceState);
        setContentView(R.layout.
activity_main);
       
mgr = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
       
txtList = (TextView)findViewById(R.id.sensorslist);
        List<Sensor> sensorList =
mgr.getSensorList(Sensor.TYPE_ALL);
        StringBuilder strBuilder =
new StringBuilder();
       
for(Sensor s: sensorList){
            strBuilder.append(s.getName()+
"\n");
        }
       
txtList.setVisibility(View.VISIBLE);
        
txtList.setText(strBuilder);
    }
}

If you observe above code, we used SensorManager class to identify and get the list of available sensors on a device.

Output of Android Sensors Example

When we run the above program in the android studio we will get the result as shown below.

 

Android Sensors Example Result

 

If you observe above result, we got all the available sensors on a device using android sensor framework in our android application.

 

This is how we can use android sensor framework to identify list all the available sensors on a device, checking whether the specific type of sensor exists or not, monitoring a sensor event changes, etc. based on our requirements.