You are on page 1of 9

Tut-4

Sensor Programming and Android Studio(21B12CI312)


6th Sem Elective, CSE/IT

Tut-4 (Android Sensors Programming)

Most of the android devices have built-in sensors that measure motion, orientation, and
various environmental condition. The android platform supports three broad categories
of sensors.

• Motion Sensors
• Environmental sensors
• Position sensors
Some of the sensors are hardware based and some are software based sensors.
Whatever the sensor is, android allows us to get the raw data from these sensors and
use it in our application.

Table 1. Sensor types supported by the Android platform.


Sensor Type Description Common
Uses
TYPE_ACCELEROMET Hardware Measures the acceleration force Motion
ER in m/s2 that is applied to a device detection
on all three physical axes (x, y, (shake, tilt,
and z), including the force of etc.).
gravity.
TYPE_AMBIENT_TEMP Hardware Measures the ambient room Monitoring
ERATURE temperature in degrees Celsius air
(°C). See note below. temperatur
es.
TYPE_GRAVITY Software Measures the force of gravity in Motion
or m/s2 that is applied to a device detection
Hardware on all three physical axes (x, y, (shake, tilt,
z). etc.).
TYPE_GYROSCOPE Hardware Measures a device's rate of Rotation
rotation in rad/s around each of detection
ANDROID SENSOR PROGRAMMING

the three physical axes (x, y, and (spin, turn,


z). etc.).
TYPE_LIGHT Hardware Measures the ambient light level Controlling
(illumination) in lx. screen
brightness
.
TYPE_LINEAR_ACCEL Software Measures the acceleration force Monitoring
ERATION or in m/s2 that is applied to a device acceleratio
Hardware on all three physical axes (x, y, n along a
and z), excluding the force of single axis.
gravity.
TYPE_MAGNETIC_FIE Hardware Measures the ambient Creating a
LD geomagnetic field for all three compass.
physical axes (x, y, z) in μT.
TYPE_ORIENTATION Software Measures degrees of rotation Determinin
that a device makes around all g device
three physical axes (x, y, z). As position.
of API level 3 you can obtain the
inclination matrix and rotation
matrix for a device by using the
gravity sensor and the
geomagnetic field sensor in
conjunction with
the getRotationMatrix() method.
TYPE_PRESSURE Hardware Measures the ambient air Monitoring
pressure in hPa or mbar. air
pressure
changes.
TYPE_PROXIMITY Hardware Measures the proximity of an Phone
object in cm relative to the view position
screen of a device. This sensor during a
is typically used to determine call.
whether a handset is being held
up to a person's ear.
TYPE_RELATIVE_HUM Hardware Measures the relative ambient Monitoring
IDITY humidity in percent (%). dewpoint,
absolute,
and
relative
humidity.
TYPE_ROTATION_VEC Software Measures the orientation of a Motion
TOR or device by providing the three detection
Hardware elements of the device's rotation and
vector. rotation
detection.
TYPE_TEMPERATURE Hardware Measures the temperature of the Monitoring
device in degrees Celsius (°C). temperatur
This sensor implementation es.
varies across devices and this

6th Sem CSE/IT 2 Dr. Hema N


ANDROID SENSOR PROGRAMMING

sensor was replaced with


the TYPE_AMBIENT_TEMPER
ATURE sensor in API Level 14

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.

Android provides SensorManager and Sensor classes to use the sensors in our
application. In order to use sensors, first thing you need to do is to instantiate the object
of SensorManager class. It can be achieved as follows.
SensorManager sMgr;
sMgr = (SensorManager)this.getSystemService(SENSOR_SERVICE);
The next thing you need to do is to instantiate the object of Sensor class by calling the
getDefaultSensor() method of the SensorManager class. Its syntax is given below
Sensor light;
light = sMgr.getDefaultSensor(Sensor.TYPE_LIGHT);

6th Sem CSE/IT 3 Dr. Hema N


ANDROID SENSOR PROGRAMMING

Once that sensor is declared , you need to register its listener and override two methods
which are onAccuracyChanged and onSensorChanged. Its syntax is as follows
sMgr.registerListener(this,light,SensorManager.SENSOR_DELAY_NORMAL);
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}

public void onSensorChanged(SensorEvent event) {


}

Getting list of sensors supported


You can get a list of sensors supported by your device by calling the getSensorList
method, which will return a list of sensors containing their name and version number
and much more information. You can then iterate the list to get the information. Its
syntax is given below −
sMgr = (SensorManager)this.getSystemService(SENSOR_SERVICE);
List<Sensor> list = sMgr.getSensorList(Sensor.TYPE_ALL);
for(Sensor sensor: list){
}

Example : Light Sensor

This app will read the raw virtual/real Light Sensor data and displays
on the screen.

6th Sem CSE/IT 4 Dr. Hema N


ANDROID SENSOR PROGRAMMING

package com.example.lightsensor;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Service;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity implements SensorEventListener {


TextView textview;
SensorManager sensorManager;
Sensor sensor;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main );
textview=(TextView)findViewById(R.id.textview );

sensorManager=(SensorManager) getSystemService(Service.SENSOR_SERVICE );
sensor=sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_NORMAL );

@Override

6th Sem CSE/IT 5 Dr. Hema N


ANDROID SENSOR PROGRAMMING

public void onSensorChanged(SensorEvent event) {


if (event.sensor.getType() == Sensor.TYPE_LIGHT ) {
textview.setText("" + event.values[0]);

}
}

@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {

}
}

Example: Temperature Sensors

6th Sem CSE/IT 6 Dr. Hema N


ANDROID SENSOR PROGRAMMING

Code:
package com.example.tempsensor;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Service;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity implements SensorEventListener {


private TextView textview;
private SensorManager sensorManager1;
private Sensor TempSensor;
private Boolean isTempSensorAvailable;

@Override
protected void onCreate(Bundle savedInstanceState) {

6th Sem CSE/IT 7 Dr. Hema N


ANDROID SENSOR PROGRAMMING

super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main );

textview = findViewById(R.id.textview);
sensorManager1=(SensorManager)getSystemService(Context.SENSOR_SERVICE );
if(sensorManager1.getDefaultSensor(Sensor.TYPE_AMBIENT_TEMPERATURE )!=null)
{
TempSensor=sensorManager1.getDefaultSensor(Sensor.TYPE_AMBIENT_TEMPERATURE );
isTempSensorAvailable=true;
}else
{
textview.setText("Temperature Sensors is not Available");
isTempSensorAvailable=false;
}

@Override
public void onSensorChanged(SensorEvent event) {
textview.setText(event.values[0]+"°C");

@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {

@Override
protected void onResume() {
super.onResume();
if(isTempSensorAvailable){
sensorManager1.registerListener(this,TempSensor,SensorManager.SENSOR_DELAY_NORMAL );

@Override

6th Sem CSE/IT 8 Dr. Hema N


ANDROID SENSOR PROGRAMMING

protected void onPause() {


super.onPause();
if(isTempSensorAvailable){
sensorManager1.unregisterListener(this);
}
}
}

Reference:

1. https://developer.android.com/guide/topics/sensors/sensors_overview
2. https://www.youtube.com/watch?v=dfTeS41BbbI
3. https://www.youtube.com/watch?v=JKuTnuUsKOI

6th Sem CSE/IT 9 Dr. Hema N

You might also like