Support free tutorials

Quick links

Android Sensor - Tutorial

Lars Vogel

Version 0.4


Android Sensor

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

Table of Contents

1. Android Sensors
1.1. SensorManager
1.2. Sensor listener
2. Tutorial: Accelerometer
3. Tutorial: Building a compass
4. About this website
5. Links and Literature
5.1. Android Resources
5.2. vogella GmbH training and consulting support

1. Android Sensors

1.1. SensorManager

Android Sensors 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 takes the sensor type and the delay defined as constants on SensorManager as parameters.

1.2. Sensor listener

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 power, you can 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 called with an activity called SensorTestActivity.

Change your layout file to the following code.

<?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 your activity class to the following code.


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); 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 = event.timestamp; 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 called 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 direction // 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); } } }

4. About this website

5. Links and Literature

5.2. vogella GmbH training and consulting support

The vogella company provides comprehensive training and education services from experts in the areas of Eclipse RCP, Android, Git, Java, Gradle and Spring. We offer both public and inhouse training. Whichever course you decide to take, you are guaranteed to experience what many before you refer to as “The best IT class I have ever attended”. The vogella company offers expert consulting services, development support and coaching. Our customers range from Fortune 100 corporations to individual developers.