Pr.Pg Next Pg

Sensors tutorials

 

Overview

  • Most Android-powered devices have built-in sensors that measure motion, orientation, and various environmental conditions.

  • These sensors are capable of providing raw data with high precision and accuracy, and are useful if you want to monitor three-dimensional device movement or positioning, or you want to monitor changes in the ambient environment near a device.

  • For example, a game might track readings from a device's gravity sensor to infer complex user gestures and motions, such as tilt, shake, rotation, or swing.

  • Likewise, a weather application might use a device's temperature sensor and humidity sensor to calculate and report the dewpoint, or a travel application might use the geomagnetic field sensor and accelerometer to report a compass bearing.

  • The Sensor class defines several constants for accessing the different sensors. Some are listed below:

Sensor.TYPE_GYROSCOPE

Sensor.TYPE_MAGNETIC_FIELD

Sensor.TYPE_ORIENTATION

Sensor.TYPE_ACCELEROMETER

  • 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.

Sensor Framework

  • You can access these sensors and acquire raw sensor data by using the Android sensor framework. The sensor framework is part of the android.hardware package and includes the following classes and interfaces:

SensorManager

  • You can use this class to create an instance of the sensor service. This class provides various methods for accessing and listing sensors, registering and unregistering sensor event listeners, and acquiring orientation information. This class also provides several sensor constants that are used to report sensor accuracy, set data acquisition rates, and calibrate sensors.

Sensor

  • You can use this class to create an instance of a specific sensor. This class provides various methods that let you determine a sensor's capabilities.

SensorEvent

  • The system uses this class to create a sensor event object, which provides information about a sensor event. A sensor event object includes the following information: the raw sensor data, the type of sensor that generated the event, the accuracy of the data, and the timestamp for the event.

SensorEventListener

  • You can use this interface to create two callback methods that receive notifications (sensor events) when sensor values change or when sensor accuracy changes.

  • 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.

 

Example

  • The accelerometer is what senses you turning/tilting your phone.

  • A component that detects movements, including shaking, for use in game-playing.

  • We now build an application in which we will have a ball which will move as we tilt the phone.

  • Below is code for the activity.

 

Accelerometer.java

 

package com.example.helloandroid;

 

import android.app.Activity;

import android.content.Context;

import android.graphics.Bitmap;

import android.graphics.BitmapFactory;

import android.graphics.Canvas;

import android.hardware.Sensor;

import android.hardware.SensorEvent;

import android.hardware.SensorEventListener;

import android.hardware.SensorManager;

import android.os.Bundle;

import android.view.SurfaceHolder;

import android.view.SurfaceView;

 

public class Accelerometer extends Activity implements SensorEventListener {

float x, y, sensorX, sensorY;

SensorManager sm;

Bitmap bm;

MySurfaceClass surface;

@Override

protected void onCreate(Bundle savedInstanceState) {

// TODO Auto-generated method stub

super.onCreate(savedInstanceState);

surface = new MySurfaceClass(this);

sm = (SensorManager) getSystemService(Context.SENSOR_SERVICE);

if (sm.getSensorList(Sensor.TYPE_ACCELEROMETER).size() != 0) {

Sensor s = sm.getSensorList(Sensor.TYPE_ACCELEROMETER).get(0);

sm.registerListener(this, s, SensorManager.SENSOR_DELAY_NORMAL);

}

bm = BitmapFactory.decodeResource(getResources(), R.drawable.ball);

x = y = sensorX = sensorY = 0;

surface.resume();

setContentView(surface);

}

 

public class MySurfaceClass extends SurfaceView implements Runnable {

 

SurfaceHolder holder;

Thread mythread = null;

boolean running = false;

 

public MySurfaceClass(Context context) {

// TODO Auto-generated constructor stub

super(context);

holder = getHolder();

}

 

@Override

public void run() {

// TODO Auto-generated method stub

while (running) {

if (!holder.getSurface().isValid())

continue;

Canvas mycanvas = holder.lockCanvas();

mycanvas.drawRGB(120, 254, 36);

float centerY = mycanvas.getHeight()/2;

float centerX = mycanvas.getWidth()/2;

mycanvas.drawBitmap(bm,centerX + sensorX*50 , centerY + sensorY*50, null);

holder.unlockCanvasAndPost(mycanvas);

 

}

}

 

public void pause() {

running = false;

while (true) {

try {

mythread.join();

} catch (InterruptedException e) {

e.printStackTrace();

}

break;

}

 

}

public void resume() {

running = true;

mythread = new Thread(this);

mythread.start();

}

}

 

@Override

public void onAccuracyChanged(Sensor sensor, int accuracy) {

// TODO Auto-generated method stub

 

}

 

@Override

public void onSensorChanged(SensorEvent event) {

// TODO Auto-generated method stub

try {

Thread.sleep(16);

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

sensorX = event.values[0];

sensorY = event.values[1];

 

}

@Override

protected void onPause() {

// TODO Auto-generated method stub

super.onPause();

surface.pause();

sm.unregisterListener(this);

}

}

 

  • We basically have used the same thread as in the previous example.

  • Within the onCreate() method we create SensorManager which lets us access the various sensors in the device.

  • We then check if the accelerometer sensor is there in the device and tif yes then we create a Sensor object.

  • We then use the SensorRegister() method to register the list of sensors(in this case only one).

  • We also set the rate i.e how fast the changes will take place.

  • Now while drawing on the canvas we change the postion of the ball depending upon the postions which we get from the sensor from the onSensorChanged() method.

  • Below are the Screenshots of the application. The ball will change postion when the phone is tilted.

 

Pr.Pg border                                              Next Pg