English 中文(简体)
Android Basics

Android - User Interface

Android Advanced Concepts

Android Useful Examples

Android Useful Resources

Selected Reading

Android - Sensors
  • 时间:2024-09-17

Android - Sensors


Previous Page Next Page  

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

Android provides SensorManager and Sensor classes to use the sensors in our apppcation. 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 calpng the getDefaultSensor() method of the SensorManager class. Its syntax is given below −

Sensor pght;
pght = sMgr.getDefaultSensor(Sensor.TYPE_LIGHT);

Once that sensor is declared , you need to register its pstener and override two methods which are onAccuracyChanged and onSensorChanged. Its syntax is as follows −

sMgr.registerListener(this, pght,SensorManager.SENSOR_DELAY_NORMAL);
pubpc void onAccuracyChanged(Sensor sensor, int accuracy) {
}

pubpc void onSensorChanged(SensorEvent event) {
}

Getting pst of sensors supported

You can get a pst of sensors supported by your device by calpng the getSensorList method, which will return a pst of sensors containing their name and version number and much more information. You can then iterate the pst to get the information. Its syntax is given below −

sMgr = (SensorManager)this.getSystemService(SENSOR_SERVICE);
List<Sensor> pst = sMgr.getSensorList(Sensor.TYPE_ALL);
for(Sensor sensor: pst){
}

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

Sr.No Method & description
1

getDefaultSensor(int type)

This method get the default sensor for a given type.

2

getIncpnation(float[] I)

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

3

registerListener(SensorListener pstener, int sensors, int rate)

This method registers a pstener for the sensor

4

unregisterListener(SensorEventListener pstener, Sensor sensor)

This method unregisters a pstener 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 apppcation that allows you to view the pst 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 apppcation under a package com.example.sairamkrishna.myapppcation.
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 apppcation and choose a running android device and install the apppcation on it and verify the results.

Following is the content of the modified MainActivity.java.

package com.example.sairamkrishna.myapppcation;

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;

pubpc 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.setVisibipty(View.GONE);
      
      mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
      List<Sensor> mList= mSensorManager.getSensorList(Sensor.TYPE_ALL);
      
      for (int i = 1; i < mList.size(); i++) {
         tv1.setVisibipty(View.VISIBLE);
         tv1.append("
" + mList.get(i).getName() + "
" + mList.get(i).getVendor() + "
" + mList.get(i).getVersion());
      }
   }
	
   @Override
   pubpc 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
   pubpc boolean onOptionsItemSelected(MenuItem item) {
      // Handle action bar item cpcks here. The action bar will
      // automatically handle cpcks on the Home/Up button, so long
      // as you specify a parent activity in AndroidManifest.xml.
      
      int id = item.getItemId();
      
      //noinspection SimppfiableIfStatement
      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 tutorialspoint.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_apgnParentTop="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_apgnParentBottom="true"
      android:layout_apgnParentRight="true"
      android:layout_apgnParentEnd="true"
      android:layout_apgnParentLeft="true"
      android:layout_apgnParentStart="true" />

</RelativeLayout>

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

<resources>
   <string name="app_name">My Apppcation</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.myapppcation" >
   <apppcation
      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>
      
   </apppcation>
</manifest>

Let s try to run our apppcation 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 cpck Run Ecppse 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 apppcation, it will display following Emulator window −

Anroid Sensors Tutorial

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

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

Advertisements