[Android] The gyroscope sensor

In this lesson, you will learn to use the gyroscope sensor.

For this, you will use the SensorManager and the sensor type TYPE_GYROSCOPE.

To use the gyroscope sensor, you have to get the sensor manager with the method getSystemService() then get the sensor by default of type TYPE_GYROSCOPE.

SensorManager sensorManager = (SensorManager)this.getSystemService (SENSOR_SERVICE);
Sensor sensorGyroscope = sensorManager.getDefaultSensor (Sensor.TYPE_GYROSCOPE);

To get the values ofthe gyroscope, you have to implement SensorEventListener and the methods onAccuracyChanged() and onSensorChanged(). With this method, you can get the values of the sensor :

extends Activity implements SensorEventListener {
public void onAccuracyChanged (Sensor sensor, int accuracy) {
}
public void onSensorChanged (SensorEvent event) {
  // Valeurs : event.values [0], event.values [1], event.values [2]
}

When the application is paused (onPause() called) and when it’s resumed (onResume() called), you have to respectively unregister the listener and register it :

protected void onResume() {
  sensorManager.registerListener (this, sensorGyroscope, SensorManager.SENSOR_DELAY_GAME);
  super.onResume();
}
protected void onPause() {
  sensorManager.unregisterListener (this, sensorGyroscope);
  super.onPause();
}

Layout main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"  
android:layout_height="fill_parent" >
<TextView
    android:id="@+id/tv_output"
    android:layout_width="fill_parent"
    android:layout_height="match_parent" />
</LinearLayout>

Fichier Main.java

public class Main extends Activity implements SensorEventListener {
       
  private SensorManager sensorManager;
  private Sensor sensorGyroscope;
  private TextView tv_output;
  public void onCreate (Bundle savedInstanceState) {
    super.onCreate (savedInstanceState);
    setContentView (R.layout.main);
    tv_output = (TextView)findViewById (R.id.tv_output);
    sensorManager = (SensorManager)this.getSystemService (SENSOR_SERVICE);
    sensorGyroscope = sensorManager.getDefaultSensor (Sensor.TYPE_GYROSCOPE);
  }
  public void onSensorChanged (SensorEvent event) {
    tv_output.setText ("0: " + event.values [0] + "\\n" + "1: " + event.values [1] + "\\n" + "2: " + event.values [2] + "\\n");
  }
  
public void onAccuracyChanged (Sensor sensor, int accuracy) {
  }
  protected void onResume() {
    sensorManager.registerListener (this, sensorGyroscope, SensorManager.SENSOR_DELAY_GAME);
    super.onResume();
  }
  protected void onPause() {
    sensorManager.unregisterListener (this, sensorGyroscope);
    super.onPause();
  }
}

Comments

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×