Accessing the Accelerometer

Tutorials with advanced 'difficulty' and more Lines of Code.

Accessing the Accelerometer

Accessing the Accelerometer

What is this: Your will learn how to access the Accelerometer

Currently the emulator does not support the emulation of an accelerometer (it just returns [0, 0, 0] what is a Free-Fall ). But when the functionality is available I will build a Class, where you can register, for special events, like, when the device is being shaken or similar.

Problems/Questions: post right below...

Difficulty: 2 of 5

Description: The accelerometer values indicate the acceleration in units of 1 = 1g = 9.8 m/s[sup]2[/sup] along the X, Y, and Z axes. With the device lying flat on a horizontal surface in front of the user, oriented so the screen is readable by the user in the normal fashion, the X axis goes from left to right, the Y axis goes from the user toward the device, and the Z axis goes upwards perpendicular to the surface.

Acceleration is defined such that a device in free fall has an accleration value of (0, 0, 0). Thus a stationary device will have an acceleration value of (0, 0, -1) since it is being acted on with 1g of force by the Earth's gravity. When the device is stationary, the acceleration vector will thus indicate the downward direction.

0.) So I created a small wrapper around the basic-functionality of Sensor-Reading, that will save you some lines:

Using java Syntax Highlighting
1. import android.hardware.Sensors;
2.
4.
5.         /** True when the Accelerometer-functionality is basically available. */
6.         boolean accelerometerAvailable = false;
7.         boolean isEnabled = false;
Parsed in 0.010 seconds, using GeSHi 1.0.8.4

1.) Constructing a AccelerometerReader which does some initial work:
Using java Syntax Highlighting
1.         /**
2.          * Sets up an AccelerometerReader. Checks if Accelerometer is available on
3.          * this device and throws UnsupportedOperationException if not .
4.          *
5.          * @param doEnable :
6.          *            enables the devices Accelerometer
7.          *            initially (if sensor available)
8.          * @throws UnsupportedOperationException
9.          *             if Accelerometer is not available on this device.
10.          */
12.                         throws UnsupportedOperationException {
13.
14.                 /* Check once here in the constructor if an
15.                  * Accelerometer is available on this device. */
16.                 for (String aSensor : Sensors.getSupportedSensors())
17.                         if (aSensor.equals(Sensors.SENSOR_ACCELEROMETER))
18.                                 accelerometerAvailable = true;
19.
20.                 if (!accelerometerAvailable)
21.                         throw new UnsupportedOperationException(
22.                                         "Accelerometer is not available.");
23.
24.                 if (doEnable)
25.                         setEnableAccelerometer(true);
26.         }
Parsed in 0.010 seconds, using GeSHi 1.0.8.4

2.) Dis/Enabling of the underlying Accelerometer:
Using java Syntax Highlighting
1.         /**
2.          * En/Dis-able the Accelerometer.
3.          *
4.          * @param doEnable
5.          *            <code>true</code> for enable.<br>
6.          *            <code>false</code> for disable.
7.          * @throws UnsupportedOperationException
8.          */
9.         public void setEnableAccelerometer(boolean doEnable)
10.                         throws UnsupportedOperationException {
11.                 if (!accelerometerAvailable)
12.                         throw new UnsupportedOperationException(
13.                                         "Accelerometer is not available.");
14.
15.                 /* If should be enabled and not already is: */
16.                 if (doEnable && !this.isEnabled) {
17.                         Sensors.enableSensor(Sensors.SENSOR_ACCELEROMETER);
18.                         this.isEnabled = true;
19.                 } else /* If should be disabled and not already is: */
20.                 if (!doEnable && this.isEnabled) {
21.                         Sensors.disableSensor(Sensors.SENSOR_ACCELEROMETER);
22.                         this.isEnabled = false;
23.                 }
24.         }
Parsed in 0.011 seconds, using GeSHi 1.0.8.4

3.) Readign out the actual values:
Using java Syntax Highlighting
1.         /**
2.          * Read out the values currently provided by the Accelerometer.
3.          *
4.          * @return the current Accelerometer-values.
5.          * @throws UnsupportedOperationException
6.          *             if Accelerometer is not available on this device.
7.          * @throws IllegalStateException
8.          *             if Accelerometer was set to disabled.
9.          */
10.         public float[] readAccelerometer() throws UnsupportedOperationException, IllegalStateException {
11.                 if (!accelerometerAvailable)
12.                         throw new UnsupportedOperationException(
13.                                         "Accelerometer is not available.");
14.
15.                 if (!this.isEnabled)
16.                         throw new IllegalStateException(
17.                                         "Accelerometer was set to disabled!");
18.                 /* Get number of sensor-values the sensor will return. Could be
19.                  * variable, depending of the amount of axis (1D, 2D or 3D
20.                  * accelerometer). */
21.                 int sensorValues = Sensors
22.                                 .getNumSensorValues(Sensors.SENSOR_ACCELEROMETER);
23.                 float[] out = new float[sensorValues];
24.
25.                 /* Make the OS fill the array we passed. */
27.
28.                 /* And return it. */
29.                 return out;
30.         }
31. }
Parsed in 0.011 seconds, using GeSHi 1.0.8.4

Thats it

The full source:

Using java Syntax Highlighting
1. package org.anddev.dummyproject;
2.
3. import android.hardware.Sensors;
4.
6.
7.         /** True when the Accelerometer-functionality is basically available. */
8.         boolean accelerometerAvailable = false;
9.         boolean isEnabled = false;
10.
11.         /**
12.          * Sets up an AccelerometerReader. Checks if Accelerometer is available on
13.          * this device and throws UnsupportedOperationException if not .
14.          *
15.          * @param doEnable :
16.          *            enables the devices Accelerometer
17.          *            initially (if sensor available)
18.          * @throws UnsupportedOperationException
19.          *             if Accelerometer is not available on this device.
20.          */
22.                         throws UnsupportedOperationException {
23.
24.                 /* Check once here in the constructor if an
25.                  * Accelerometer is available on this device. */
26.                 for (String aSensor : Sensors.getSupportedSensors())
27.                         if (aSensor.equals(Sensors.SENSOR_ACCELEROMETER))
28.                                 accelerometerAvailable = true;
29.
30.                 if (!accelerometerAvailable)
31.                         throw new UnsupportedOperationException(
32.                                         "Accelerometer is not available.");
33.
34.                 if (doEnable)
35.                         setEnableAccelerometer(true);
36.         }
37.
38.         /**
39.          * En/Dis-able the Accelerometer.
40.          *
41.          * @param doEnable
42.          *            <code>true</code> for enable.<br>
43.          *            <code>false</code> for disable.
44.          * @throws UnsupportedOperationException
45.          */
46.         public void setEnableAccelerometer(boolean doEnable)
47.                         throws UnsupportedOperationException {
48.                 if (!accelerometerAvailable)
49.                         throw new UnsupportedOperationException(
50.                                         "Accelerometer is not available.");
51.
52.                 /* If should be enabled and not already is: */
53.                 if (doEnable && !this.isEnabled) {
54.                         Sensors.enableSensor(Sensors.SENSOR_ACCELEROMETER);
55.                         this.isEnabled = true;
56.                 } else /* If should be disabled and not already is: */
57.                 if (!doEnable && this.isEnabled) {
58.                         Sensors.disableSensor(Sensors.SENSOR_ACCELEROMETER);
59.                         this.isEnabled = false;
60.                 }
61.         }
62.
63.         /**
64.          * Read out the values currently provided by the Accelerometer.
65.          *
66.          * @return the current Accelerometer-values.
67.          * @throws UnsupportedOperationException
68.          *             if Accelerometer is not available on this device.
69.          * @throws IllegalStateException
70.          *             if Accelerometer was set to disabled.
71.          */
72.         public float[] readAccelerometer() throws UnsupportedOperationException, IllegalStateException {
73.                 if (!accelerometerAvailable)
74.                         throw new UnsupportedOperationException(
75.                                         "Accelerometer is not available.");
76.
77.                 if (!this.isEnabled)
78.                         throw new IllegalStateException(
79.                                         "Accelerometer was set to disabled!");
80.                 /* Get number of sensor-values the sensor will return. Could be
81.                  * variable, depending of the amount of axis (1D, 2D or 3D
82.                  * accelerometer). */
83.                 int sensorValues = Sensors
84.                                 .getNumSensorValues(Sensors.SENSOR_ACCELEROMETER);
85.                 float[] out = new float[sensorValues];
86.
87.                 /* Make the OS fill the array we passed. */
89.
90.                 /* And return it. */
91.                 return out;
92.         }
93. }
Parsed in 0.013 seconds, using GeSHi 1.0.8.4

Regards,
plusminus

| Android Development Community / Tutorials

plusminus

Posts: 2688
Joined: Wed Nov 14, 2007 8:37 pm
Location: Schriesheim, Germany

hi, plusminus

could u provide a simple application that use your AccelerometerReader, such as change a text in TextView when the phone is shaked. or is it not possible with the current emulator?

thanks
nico
Junior Developer

Posts: 19
Joined: Tue Nov 27, 2007 10:33 am
Location: Indonesia

Hello nico,

currently there is no emulation for an accelerometer.

Regards,
plusminus

| Android Development Community / Tutorials

plusminus

Posts: 2688
Joined: Wed Nov 14, 2007 8:37 pm
Location: Schriesheim, Germany

Hi!

OpenIntents has now the brand-new SensorSimulator! Now you can easily test your accelerometer-based application:

Try it out online here:
http://www.openintents.org/sensorsimulator

The phone is no longer freely falling, with the boring acceleration=(0,0,0), but you can receive real-time sensor data just by dragging around the simulated phone with the mouse.

Peli

PS: PlusMinus, you should probably change the following line in your code above:
if (aSensor.equals(Sensors.SENSOR_ACCELEROMETER))
to
if (aSensor.contentEquals(Sensors.SENSOR_ACCELEROMETER))
since the former version will compare pointer addresses, but the latter version compares strings. (just in case there are two equal strings, but with different address...)
Peli
Junior Developer

Posts: 17
Joined: Thu Dec 27, 2007 10:54 am

PlusMinus,

By the way, I used your pyramid for the OpenGLSensors demo I hope that is ok, and I don't violate any copyright

Peli
Peli
Junior Developer

Posts: 17
Joined: Thu Dec 27, 2007 10:54 am

Hello Peli,

nice to see the code reused.

Actually I'm pretty sure, that .equals also does a Content-Check for Equality.
Comparing by "==" would do a Pointer(Reference)-Comparison.

Regards,
plusminus

| Android Development Community / Tutorials

plusminus

Posts: 2688
Joined: Wed Nov 14, 2007 8:37 pm
Location: Schriesheim, Germany

Hi

Thanks Peli for this wonderful SensorSimulator! . Also Thanks to plusminus for showing wonderful code.

Regrds

nit1507

nit1507
Freshman

Posts: 6
Joined: Wed Jan 09, 2008 4:27 pm
Location: Chennai, India

plusminus wrote:Actually I'm pretty sure, that .equals also does a Content-Check for Equality.
Comparing by "==" would do a Pointer(Reference)-Comparison.

I guess you are right. I must have done something stupid , like comparing a string to a CharSequence (if that is a test that fails...). In any case, I had some trouble some days ago and that got resolved by changing equals to contentEquals, but reading through the documentation, I agree with you that equals should already compare the strings, so probably my mistake was somewhere else and I had not noticed it...

nit1507, thanks for the positive feedback

Peli
Peli
Junior Developer

Posts: 17
Joined: Thu Dec 27, 2007 10:54 am

Hello peli,

java.lang.String implements the CharSeqeunce-Interface, so the following code is correct:
Using java Syntax Highlighting
1.                 String s = "hello";
2.                 CharSequence cs = "hello";
3.
4.                 boolean b = s.equals(cs); // b will be 'true'
Parsed in 0.010 seconds, using GeSHi 1.0.8.4

Regards,
plusminus

| Android Development Community / Tutorials

plusminus

Posts: 2688
Joined: Wed Nov 14, 2007 8:37 pm
Location: Schriesheim, Germany

Application error: org.anddev.dummyproject

Hello i am getting an error while starting the application -

"An error has occurred in process org.anddev.dummyproject . Unable to instantiate activity ."

Can somebody tell me why has this problem occurred ??

Abhinav

parashar.iiit
Junior Developer

Posts: 10
Joined: Sat Feb 02, 2008 12:51 pm

Hello parashar.iiit,

is there no further detail to the Exception

Just tried my code again and it worked fine.
Perhaps provide some code (if you are sure it has sth. to do with my Accelerometer-Reader here, otherwise in a new topic)

Regards,
plusminus

| Android Development Community / Tutorials

plusminus

Posts: 2688
Joined: Wed Nov 14, 2007 8:37 pm
Location: Schriesheim, Germany

Hello plusminus,
Thanks for your reply. Actually first time i am facing this error .I also just tried the code again but the same error is coming again .

An error has occured in process org.anddev.dummyproject. Unable to
instantiate activity
java.lang.InstantiationException:

I guess now you can understand my problem .

Thanks

parashar.iiit
Junior Developer

Posts: 10
Joined: Sat Feb 02, 2008 12:51 pm

Hello parashar.iiit,

the code above is no Activity it just a normal Java-Class you use.
i.e. you'll have it as a field in your Activity:
Using java Syntax Highlighting
1. public class TestLayout extends Activity {
2.
3.
4.
6.
7.
8.
9.         @Override
10.
11.         public void onCreate(Bundle icicle) {
12.
13.                 super.onCreate(icicle);
14.
15.                 this.setContentView(R.layout.main);
16.
17.                 // Perhaps make a button-OnClick show the Accelerometer-Values in a TextView...
18.
19.         }
20.
21. }
Parsed in 0.011 seconds, using GeSHi 1.0.8.4

If not please provide the Activity where you are using the AccelerometerReader.

Regards,
plusminus

| Android Development Community / Tutorials

plusminus

Posts: 2688
Joined: Wed Nov 14, 2007 8:37 pm
Location: Schriesheim, Germany

Oh thanks pulsminus .... Its working ....Such a stupid mistake i was making ...

parashar.iiit
Junior Developer

Posts: 10
Joined: Sat Feb 02, 2008 12:51 pm

parashar.iiit wrote:Oh thanks pulsminus .... Its working ....Such a stupid mistake i was making ...

^^ Everyone makes such a fault somewhen

| Android Development Community / Tutorials

plusminus