20.08.2016 Views

Professional Android 4 Application Development

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Monitoring a Device’s Movement and Orientation x 495<br />

3. Add a calibration constant that represents the acceleration due to gravity:<br />

private final double calibration = SensorManager.STANDARD_GRAVITY;<br />

4. Create a new SensorEventListener implementation that sums the acceleration detected<br />

along each axis and negates the acceleration due to gravity. It should update the current (and<br />

possibly maximum) acceleration whenever a change in acceleration is detected:<br />

private final SensorEventListener sensorEventListener = new SensorEventListener() {<br />

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

public void onSensorChanged(SensorEvent event) {<br />

double x = event.values[0];<br />

double y = event.values[1];<br />

double z = event.values[2];<br />

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

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

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

currentAcceleration = Math.abs((float)(a-calibration));<br />

}<br />

};<br />

if (currentAcceleration > maxAcceleration)<br />

maxAcceleration = currentAcceleration;<br />

5. Update the onCreate method to get a reference to the two Text Views and the Sensor<br />

Manager:<br />

@Override<br />

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

super.onCreate(savedInstanceState);<br />

setContentView(R.layout.main);<br />

}<br />

accelerationTextView = (TextView)findViewById(R.id.acceleration);<br />

maxAccelerationTextView = (TextView)findViewById(R.id.maxAcceleration);<br />

sensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);<br />

6. Override the onResume handler to register your new Listener for accelerometer updates using<br />

the SensorManager:<br />

@Override<br />

protected void onResume() {<br />

super.onResume();<br />

Sensor accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);<br />

sensorManager.registerListener(sensorEventListener,<br />

accelerometer,<br />

SensorManager.SENSOR_DELAY_FASTEST);<br />

}

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

Saved successfully!

Ooh no, something went wrong!