Android Phone with imaginary arrows representing the X and Y axis. Z axis' direction is in front of your phone. |
First thing to do is to register a listener. The name of the listener is SensorEventListener. It has 2 methods to implement, onSensorChanged() and onAccuracyChanged(). onSensorChanged() is called whenever a new accelerometer event happens. The onAccuracyChanged() is called when the accuracy of our sensor changes.
public class AccelerometerTest
extends Activity
implements SensorEventListener
{
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
@Override
public void onSensorChanged(SensorEvent event) {
}
}
To register our listener, we need to check whether an accelerometer is installed on our Android device. We will be using a SensorManager class, which we will use to check for an accelerometer and register the listener to it. Here's the code to do all does things (place this code in your onCreate() method):
SensorManager manager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
if(manager.getSensorList(Sensor.TYPE_ACCELEROMETER).size() == 0)
{
//no accelerometer installed
}
else
{
Sensor sensor = manager.getSensorList(Sensor.TYPE_ACCELEROMETER).get(0);
if(manager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_GAME))
{
//cannot register sensor listener
}
}
Your accelerometer is now ready. We will then display the values of our device's accelerometer. The SensorEvent parameter of our onSensorChanged() method has a field member named values which is an array. SensorEvent.values[0] returns the value of X axis, SensorEvent.values[1] returns the value of Y axis, and SensorEvent.values[2] returns the value of Z axis. Try holding your phone in portrait and you will get a positive number in the Y axis. For the X axis, try holding your phone in landscape, its right side facing to the sky. Also try facing your phone's screen to the sky to get a positive number in the Z axis.
The full source code of this post is found here.
No comments:
Post a Comment