Android Sensors Tutorial

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.

  1. Motion Sensors

  2. Environmental sensors

  3. 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 sytanx 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.NoMethod & description
1getDefaultSensor(int type)
This method get the default sensor for a given type.
2getOrientation(float[] R, float[] values)
This method returns a description of the current primary clip on the clipboard but not a copy of its data.
3getInclination(float[] I)
This method computes the geomagnetic inclination angle in radians from the inclination matrix.
4registerListener(SensorListener listener, int sensors, int rate)
This method registers a listener for the sensor
5unregisterListener(SensorEventListener listener, Sensor sensor)
This method unregisters a listener for the sensors with which it is registered.
6getOrientation(float[] R, float[] values)
This method computes the device's orientation based on the rotation matrix.
7getAltitude(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.

StepsDescription
1You will use Eclipse IDE to create an Android application and name it as Sensors under a package com.example.sensors. While creating this project, make sure you Target SDK and Compile With at the latest version of Android SDK to use higher levels of APIs.
2Modify src/MainActivity.java file to add necessary code.
3Modify the res/layout/activity_main to add respective XML components.
4Modify the res/values/string.xml to add necessary string components.
5Run the application and choose a running android device and install the application on it and verify the results.

Following is the content of the modifed main activity file src/com.example.sensors/MainActivity.java.

package com.example.sensors;

import java.util.List;

import android.app.Activity;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends Activity {

   private SensorManager sMgr;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      TextView sensorsData = (TextView)findViewById(R.id.textView1);

      sMgr = (SensorManager)this.getSystemService(SENSOR_SERVICE);
      List list = sMgr.getSensorList(Sensor.TYPE_ALL);

      StringBuilder data = new StringBuilder();
      for(Sensor sensor: list){
         data.append(sensor.getName() + "\n");
         data.append(sensor.getVendor() + "\n");
         data.append(sensor.getVersion() + "\n");

   }
   sensorsData.setText(data);
}

   @Override
   public boolean onCreateOptionsMenu(Menu menu) {
      // Inflate the menu; this adds items to the action bar if it is present.
      getMenuInflater().inflate(R.menu.main, menu);
      return true;
   }

}

Following is the modified content of the xml res/layout/activity_main.xml.

<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:paddingBottom="@dimen/activity_vertical_margin"
   android:paddingLeft="@dimen/activity_horizontal_margin"
   android:paddingRight="@dimen/activity_horizontal_margin"
   android:paddingTop="@dimen/activity_vertical_margin"
   tools:context=".MainActivity" >

   <ScrollView
      android:id="@+id/scrollView1"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignParentLeft="true"
      android:layout_alignParentTop="true"
      android:layout_marginLeft="16dp"
      android:layout_marginTop="16dp" >

   <LinearLayout
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:orientation="vertical" >

   <TextView
      android:id="@+id/textView1"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Medium Text"
      android:textAppearance="?android:attr/textAppearanceMedium" />

      </LinearLayout>
   </ScrollView>

</RelativeLayout>

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

<?xml version="1.0" encoding="utf-8"?>
<resources>

   <string name="app_name">Sensors</string>
   <string name="action_settings">Settings</string>
   <string name="hello_world">Hello world!</string>
   <string name="list">List of sensors supported</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.sensors"
   android:versionCode="1"
   android:versionName="1.0" >

   <uses-sdk
      android:minSdkVersion="8"
      android:targetSdkVersion="17" />

   <application
      android:allowBackup="true"
      android:icon="@drawable/ic_launcher"
      android:label="@string/app_name"
      android:theme="@style/AppTheme" >
      <activity
         android:name="com.example.sensors.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 Sensor application we just modified. I assume you had created your AVD while doing environment setup. To run the app from Eclipse, open one of your project's activity files and click Run Eclipse Run Icon icon from the toolbar. Eclipse 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 differnet because the output depends upon the number of sensors supported by your device.



Advertisements
Advertisements