Android Projects

Android Development Books


Android Sensor Tutorial

                            By  Lars Vogel-

Android Sensor
This tutorial describes how to use the Androids Sensor manager. The tutorial is based on Eclipse 3.6, Java 1.6 and Android 2.3.3 (Gingerbread).

1. Android Sensors

Android supports several sensors via the SensorManager, for example the accelerometer. Unfortunately you cannot test the accelerometer on the Android emulator.
You can access a SensorManager via getSystemService(SENSOR_SERVICE). The Sensor class defines several constants for accessing the different sensors.

You can access the Sensor via the sensorManager.getDefaultSensor() method, which take as parameters the sensor type and the deplay defined as constants on SensorManager.
Once you acquired a sensor, you can register a SensorEventListener object on it. This listener will get informed, if the sensor data changes.
To avoid the unnecessary usage of battery you register your listener in the onResume() method and de-register it in the onPause() method.

2. Tutorial: Accelerometer

We will build an application which will change its background color, if it is shuffled. Create a new Android project "" with an Activity called SensorTestActivity.
Change your layout main.xml to the following.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""
    android:orientation="vertical" >

        android:text="Shake to get a toast and to switch color" />


Change the your Activity to the following. 


import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;

public class SensorTestActivity extends Activity implements SensorEventListener {
 private SensorManager sensorManager;
 private boolean color = false;
 private View view;
 private long lastUpdate;

/** Called when the activity is first created. */
@Override public void onCreate(Bundle savedInstanceState) { requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); super.onCreate(savedInstanceState); setContentView(R.layout.main); view = findViewById(; view.setBackgroundColor(Color.GREEN); sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE); sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL); lastUpdate = System.currentTimeMillis(); } @Override public void onSensorChanged(SensorEvent event) { if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) { getAccelerometer(event); } } private void getAccelerometer(SensorEvent event) { float[] values = event.values; // Movement float x = values[0]; float y = values[1]; float z = values[2]; float accelationSquareRoot = (x * x + y * y + z * z) / (SensorManager.GRAVITY_EARTH * SensorManager.GRAVITY_EARTH); long actualTime = System.currentTimeMillis(); if (accelationSquareRoot >= 2) // { if (actualTime - lastUpdate < 200) { return; } lastUpdate = actualTime; Toast.makeText(this, "Device was shuffed", Toast.LENGTH_SHORT) .show(); if (color) { view.setBackgroundColor(Color.GREEN); } else { view.setBackgroundColor(Color.RED); } color = !color; } } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { } @Override protected void onResume() { super.onResume(); // register this class as a listener for the orientation and // accelerometer sensors sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL); } @Override protected void onPause() { // unregister listener super.onPause(); sensorManager.unregisterListener(this); } }

3. Tutorial: Building a compass

Create a new Android project "" with an Activity called MainActivity.
Create the following custom View class.


import android.content.Context;
import android.view.View;

public class MyCompassView extends View {

 private Paint paint;
 private float position = 0;

 public MyCompassView(Context context) {

 private void init() {
  paint = new Paint();

 protected void onDraw(Canvas canvas) {
  int xPoint = getMeasuredWidth() / 2;
  int yPoint = getMeasuredHeight() / 2;

  float radius = (float) (Math.max(xPoint, yPoint) * 0.6);
  canvas.drawCircle(xPoint, yPoint, radius, paint);
  canvas.drawRect(0, 0, getMeasuredWidth(), getMeasuredHeight(), paint);

  // 3.143 is a good approximation for the circle
    (float) (xPoint + radius
      * Math.sin((double) (-position) / 180 * 3.143)),
    (float) (yPoint - radius
      * Math.cos((double) (-position) / 180 * 3.143)), paint);

  canvas.drawText(String.valueOf(position), xPoint, yPoint, paint);

 public void updateData(float position) {
  this.position = position;


Change the coding of your Activity


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.util.Log;
import android.widget.Toast;

public class MainActivity extends Activity {

 private static SensorManager sensorService;
 private MyCompassView compassView;
 private Sensor sensor;

/** Called when the activity is first created. */
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); compassView = new MyCompassView(this); setContentView(compassView); sensorService = (SensorManager) getSystemService(Context.SENSOR_SERVICE); sensor = sensorService.getDefaultSensor(Sensor.TYPE_ORIENTATION); if (sensor != null) { sensorService.registerListener(mySensorEventListener, sensor, SensorManager.SENSOR_DELAY_NORMAL); Log.i("Compass MainActivity", "Registerered for ORIENTATION Sensor"); } else { Log.e("Compass MainActivity", "Registerered for ORIENTATION Sensor"); Toast.makeText(this, "ORIENTATION Sensor not found", Toast.LENGTH_LONG).show(); finish(); } } private SensorEventListener mySensorEventListener = new SensorEventListener() { @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { } @Override public void onSensorChanged(SensorEvent event) { // angle between the magnetic north directio // 0=North, 90=East, 180=South, 270=West float azimuth = event.values[0]; compassView.updateData(azimuth); } }; @Override protected void onDestroy() { super.onDestroy(); if (sensor != null) { sensorService.unregisterListener(mySensorEventListener); } } }

Share this post
  • Share to Facebook
  • Share to Twitter
  • Share to Google+
  • Share to Stumble Upon
  • Share to Evernote
  • Share to Blogger
  • Share to Email
  • Share to Yahoo Messenger
  • More...


Thanks for your comment

:) :-) :)) =)) :( :-( :(( :d :-d @-) :p :o :>) (o) [-( :-? (p) :-s (m) 8-) :-t :-b b-( :-# =p~ :-$ (b) (f) x-) (k) (h) (c) cheer

Related Posts Plugin for WordPress, Blogger...
© Google Android Lovers
Designed by BlogThietKe Cooperated with Duy Pham
Released under Creative Commons 3.0 CC BY-NC 3.0