Accelerometer Handler Which Side Is Up

Let's start with the easiest of all handlers: the AccelerometerHandler. Listing 5-5 shows you its code.

Listing 5-5. AccelerometerHandler.java; Performing All the Accelerometer Handling package com.badlogic.androidgames.framework.impl;

import android.content.Context; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager;

public class AccelerometerHandler implements SensorEventListener { float accelX; float accelY; float accelZ;

public AccelerometerHandler(Context context) {

SensorManager manager = (SensorManager) context

.getSystemService(Context.SENSOR_SERVICE); if (manager.getSensorList(Sensor.TYPE_ACCELER0METER),size() != 0) { Sensor accelerometer = manager.getSensorList(

Sensor.TYPE_ACCELER0METER).get(0); manager.registerListener(this, accelerometer, SensorManager. SENS0R_DELAY_GAME);

@Override public void onAccuracyChanged(Sensor sensor, int accuracy) { // nothing to do here

@Override public void onSensorChanged(SensorEvent event) { accelX = event.values[0]; accelY = event.values[1]; accelZ = event.values[2];

public float getAccelX() { return accelX;

public float getAccelY() { return accelY;

public float getAccelZ() { return accelZ;

Unsurprisingly, the class implements the SensorEventListener interface, which we used in Chapter 4. The class stores three members, holding the acceleration on each of the three accelerometer axes.

The constructor takes a Context, from which it gets a SensorManager instance to set up the event listening. The rest of the code is equivalent to what we did in the last chapter. Note that if no accelerometer is installed, the handler will happily return zero acceleration on all axes throughout its life. We thus don't need any extra error-checking or exception-throwing code.

The next two methods, onAccuracyChanged() and onSensorChanged(), should also be familiar. In the first we don't do anything, as there's nothing much to report. In the second one we fetch the accelerometer values from the provided SensorEvent and store them in the handler's members.

The final three methods simply return the current acceleration for each axis.

Note that we do not need to perform any synchronization here, even though the onSensorChanged() method might be called in a different thread. The Java memory model guarantees that writes and reads to and from primitive types such as boolean, int, or byte are atomic. In this case it's OK to rely on this fact, as we don't do anything more complex than assigning a new value. We'd need to have proper synchronization if this were not the case (e.g., if we did something with the member variables in the onSensorChanged() method.

0 0

Post a comment