14.01.2013 Views

Android™ Application Development - Bahar Ali Khan

Android™ Application Development - Bahar Ali Khan

Android™ Application Development - Bahar Ali Khan

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 10: Accessing Android Hardware<br />

Creating a Speedometer<br />

326<br />

While an accelerometer won’t tell you your current speed, you can calculate a rough estimate by monitoring<br />

changes in acceleration over time. In the following example, you’ll create a simple speedometer<br />

using the accelerometers to determine the current speed based on acceleration changes.<br />

The sensitivity and responsiveness of the hardware accelerometers will limit the accuracy and effectiveness<br />

of this application, but the techniques it uses should give you a better understanding of how to use<br />

the accelerometer sensors for something more useful.<br />

Because accelerometers measure the change in velocity in a given direction, you can establish your<br />

current speed by determining how long each acceleration value has been applied. For those mathematically<br />

inclined, you’re fi nding the second derivative of the acceleration changes.<br />

For example, if you accelerate at a steady rate of 1 m/s 2 after 10 seconds, your speed will be 10 m/s (or<br />

36 km/h). When your speed becomes steady, your acceleration should return to zero. In the real world,<br />

acceleration rarely stops and starts in an instant, nor does it remain constant, so you’ll need to adjust<br />

your velocity calculations as the measured acceleration changes.<br />

1. Start by creating a new Speedometer project with a Speedometer Activity. Modify the main.xml<br />

layout resource to display a single, centered line of large, bold text that will be used to display<br />

your current speed.<br />

<br />

<br />

<br />

/><br />

<br />

2. Within the Speedometer Activity, create instance variables to store references to the TextView<br />

and the SensorManager. Also create variables to record the current acceleration, velocity, and<br />

the last update time.<br />

SensorManager sensorManager;<br />

TextView myTextView;<br />

float appliedAcceleration = 0;<br />

float currentAcceleration = 0;<br />

float velocity = 0;<br />

Date lastUpdate;

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!