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 />

3. Create a new updateVelocity method that calculates the velocity change since the last update<br />

based on the current acceleration.<br />

private void updateVelocity() {<br />

// Calculate how long this acceleration has been applied.<br />

Date timeNow = new Date(System.currentTimeMillis());<br />

long timeDelta = timeNow.getTime()-lastUpdate.getTime();<br />

lastUpdate.setTime(timeNow.getTime());<br />

}<br />

// Calculate the change in velocity at the<br />

// current acceleration since the last update.<br />

float deltaVelocity = appliedAcceleration * (timeDelta/1000);<br />

appliedAcceleration = currentAcceleration;<br />

// Add the velocity change to the current velocity.<br />

velocity += deltaVelocity;<br />

// Convert from meters per second to miles per hour.<br />

double mph = (Math.round(velocity / 1.6 * 3.6));<br />

myTextView.setText(String.valueOf(mph) + “mph”);<br />

4. Create a new SensorListener implementation that updates the current acceleration (and<br />

derived velocity) whenever a change in acceleration is detected.<br />

Because a speedometer will most likely be used while the device is mounted vertically, with the<br />

screen face perpendicular to the ground, measure negative acceleration along the Z-axis.<br />

private final SensorListener sensorListener = new SensorListener() {<br />

double calibration - Double.NAN;<br />

};<br />

public void onSensorChanged(int sensor, float[] values) {<br />

double x = values[SensorManager.DATA_X];<br />

double y = values[SensorManager.DATA_Y];<br />

double z = values[SensorManager.DATA_Z];<br />

double a = -1*Math.sqrt(Math.pow(x, 2) +<br />

Math.pow(y, 2) +<br />

Math.pow(z, 2));<br />

if (calibration == Double.NaN)<br />

calibration = a;<br />

else {<br />

updateVelocity();<br />

currentAcceleration = (float)a;<br />

}<br />

}<br />

public void onAccuracyChanged(int sensor, int accuracy) {}<br />

5. Update the onCreate method to register your new Listener for accelerometer updates using the<br />

SensorManager. Take the opportunity to get a reference to the Text View.<br />

@Override<br />

public void onCreate(Bundle icicle) {<br />

327

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

Saved successfully!

Ooh no, something went wrong!