Game Development Reference
In-Depth Information
So how do we process the SensorEvent ? That's rather easy. The SensorEvent has a public float
array member called SensorEvent.values that holds the current acceleration values of each
of the three axes of the accelerometer. SensorEvent.values[0] holds the value of the x axis,
SensorEvent.values[1] holds the value of the y axis, and SensorEvent.values[2] holds the
value of the z axis. We discussed what is meant by these values in Chapter 3, so if you have
forgotten that, go and check out the “Input� section again.
With this information, we can write a simple test activity. All we want to do is output the
accelerometer values for each accelerometer axis in a TextView . Listing 4-6 shows how to
do this.
Listing 4-6. AccelerometerTest.java; Testing the Accelerometer API
package com.badlogic.androidgames;
import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.TextView;
public class AccelerometerTest extends Activity implements SensorEventListener {
TextView textView;
StringBuilder builder = new StringBuilder();
@Override
public void onCreate(Bundle savedInstanceState) {
super .onCreate(savedInstanceState);
textView = new TextView( this );
setContentView(textView);
SensorManager manager = (SensorManager) getSystemService(Context. SENSOR_SERVICE );
if (manager.getSensorList(Sensor. TYPE_ACCELEROMETER ).size() == 0) {
textView.setText("No accelerometer installed");
} else {
Sensor accelerometer = manager.getSensorList(
Sensor. TYPE_ACCELEROMETER ).get(0);
if (!manager.registerListener( this , accelerometer,
SensorManager. SENSOR_DELAY_GAME )) {
textView.setText("Couldn't register sensor listener");
}
}
}
public void onSensorChanged(SensorEvent event) {
builder.setLength(0);
builder.append("x: ");
builder.append(event.values[0]);
builder.append(", y: ");
 
Search WWH ::




Custom Search