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.

Sensor.TYPE_GYROSCOPE

Sensor.TYPE_MAGNETIC_FIELD

Sensor.TYPE_ORIENTATION

Sensor.TYPE_ACCELEROMETER

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
de.vogella.android.sensor
with
an
activity
called
SensorTestActivity.

Change your layout file
to the following code.

<?xml version="1.0" encoding="utf-8"?><LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical" ><TextViewandroid:id="@+id/textView"android:layout_width="match_parent"android:layout_height="match_parent"android:text="Shake to get a toast and to switch color" /></LinearLayout>