Game Development Reference
In-Depth Information
The next two methods, onAccuracyChanged() and onSensorChanged() , should be familiar. In the
first method, we don't do anything, so 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 since we aren't doing anything more complex
than assigning a new value. We'd need to have proper synchronization if this were not the case
(for example, if we did something with the member variables in the onSensorChanged() method).
CompassHandler
Just for fun, we're going to provide an example that is similar to the AccelerometerHandler , but
this time we'll give you the compass values along with the pitch and roll of the phone, as shown
in Listing 5-6. We call the compass value yaw , since that's a standard orientation term that nicely
defines the value we're seeing.
Android handles all sensors through the same interfaces, so this example shows you how to
cope with that. The only difference between Listing 5-6 and the previous accelerometer example
is the change of the sensor type to TYPE_ORIENTATION and the renaming of the fields from accel
to yaw , pitch , and roll . Otherwise, it works in the same way, and you can easily swap this code
into the game as the control handler!
Listing 5-6. CompassHandler.java; Performing All the Compass 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 CompassHandler implements SensorEventListener {
float yaw;
float pitch;
float roll;
public CompassHandler(Context context) {
SensorManager manager=(SensorManager) context
.getSystemService(Context.SENSOR_SERVICE);
if (manager.getSensorList(Sensor.TYPE_ORIENTATION).size() ! = 0) {
Sensor compass=manager.getDefaultSensor(Sensor.TYPE_ORIENTATION);
manager.registerListener( this , compass,
SensorManager.SENSOR_DELAY_GAME);
}
}
 
Search WWH ::




Custom Search