• Android Video Tutorials

Android - Sensors


Advertisements

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. For this android provides us with some classes.

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);

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){
}

Apart from the these methods, there are other methods provided by the SensorManager class for managing sensors framework. These methods are listed below −

Sr.No Method & description
1

getDefaultSensor(int type)

This method get the default sensor for a given type.

2

getInclination(float[] I)

This method computes the geomagnetic inclination angle in radians from the inclination matrix.

3

registerListener(SensorListener listener, int sensors, int rate)

This method registers a listener for the sensor

4

unregisterListener(SensorEventListener listener, Sensor sensor)

This method unregisters a listener for the sensors with which it is registered.

5

getOrientation(float[] R, float[] values)

This method computes the device's orientation based on the rotation matrix.

6

getAltitude(float p0, float p)

This method computes the Altitude in meters from the atmospheric pressure and the pressure at sea level.

Example

Here is an example demonstrating the use of SensorManager class. It creates a basic application that allows you to view the list of sensors on your device.

To experiment with this example , you can run this on an actual device or in an emulator.

Steps Description
1 You will use Android studio to create an Android application under a package com.example.sairamkrishna.myapplication.
2 Modify src/MainActivity.java file to add necessary code.
3 Modify the res/layout/activity_main to add respective XML components.
4 Run the application and choose a running android device and install the application on it and verify the results.

Following is the content of the modified MainActivity.java.

package com.example.sairamkrishna.myapplication;

import android.app.Activity;
import android.hardware.SensorManager;
import android.os.Bundle;

import android.util.Log;

import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import android.widget.TextView;

import java.util.List;
import android.hardware.Sensor;
import android.hardware.SensorManager;

public class MainActivity extends Activity {
   TextView tv1=null;
   private SensorManager mSensorManager;
   @Override
   
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      
      tv1 = (TextView) findViewById(R.id.textView2);
      tv1.setVisibility(View.GONE);
      
      mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
      List<Sensor> mList= mSensorManager.getSensorList(Sensor.TYPE_ALL);
      
      for (int i = 1; i < mList.size(); i++) {
         tv1.setVisibility(View.VISIBLE);
         tv1.append("\n" + mList.get(i).getName() + "\n" + mList.get(i).getVendor() + "\n" + mList.get(i).getVersion());
      }
   }
	
   @Override
   public boolean onCreateOptionsMenu(Menu menu) {
      // Inflate the menu; this adds items to the action bar if it is present.
      getMenuInflater().inflate(R.menu.menu_main, menu);
      return true;
   }
   
   @Override
   public boolean onOptionsItemSelected(MenuItem item) {
      // Handle action bar item clicks here. The action bar will
      // automatically handle clicks on the Home/Up button, so long
      // as you specify a parent activity in AndroidManifest.xml.
      
      int id = item.getItemId();
      
      //noinspection SimplifiableIfStatement
      if (id == R.id.action_settings) {
         return true;
      }
      return super.onOptionsItemSelected(item);
   }
}

Following is the modified content of the xml activity_main.xml.

In the below code abc indicates about the logo of howcodex.com
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
   android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
   android:paddingRight="@dimen/activity_horizontal_margin"
   android:paddingTop="@dimen/activity_vertical_margin"
   android:paddingBottom="@dimen/activity_vertical_margin"
   tools:context=".MainActivity"
   android:transitionGroup="true">
   
   <TextView android:text="Sensor " android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/textview"
      android:textSize="35dp"
      android:layout_alignParentTop="true"
      android:layout_centerHorizontal="true" />
      
   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Tutorials point"
      android:id="@+id/textView"
      android:layout_below="@+id/textview"
      android:layout_centerHorizontal="true"
      android:textColor="#ff7aff24"
      android:textSize="35dp" />
      
   <ImageView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/imageView"
      android:src="@drawable/abc"
      android:layout_below="@+id/textView"
      android:layout_centerHorizontal="true"
      android:theme="@style/Base.TextAppearance.AppCompat" />
      
   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="New Text"
      android:id="@+id/textView2"
      android:layout_below="@+id/imageView"
      android:layout_alignParentBottom="true"
      android:layout_alignParentRight="true"
      android:layout_alignParentEnd="true"
      android:layout_alignParentLeft="true"
      android:layout_alignParentStart="true" />

</RelativeLayout>

Following is the content of the res/values/string.xml.

<resources>
   <string name="app_name">My Application</string>
   <string name="hello_world">Hello world!</string>
   <string name="action_settings">Settings</string>
</resources>

Following is the content of AndroidManifest.xml file.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.sairamkrishna.myapplication" >
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:theme="@style/AppTheme" >
      
      <activity
         android:name=".MainActivity"
         android:label="@string/app_name" >
         
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
         
      </activity>
      
   </application>
</manifest>

Let's try to run our application we just modified. I assume you had created your AVD while doing environment setup. To run the app from Android studio, open one of your project's activity files and click Run Eclipse Run Icon icon from the toolbar. Android studio installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window −

Anroid Sensors Tutorial

Now if you will look at your device screen, you will see the list of sensors supported by your device along with their name and version and other information.

If you would run this application on different devices, the output would be different because the output depends upon the number of sensors supported by your device.

Advertisements