Accelerometer API : Sensor « Hardware « Android






Accelerometer API

   
package app.test;

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 Test 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");
      }
    }
  }

  @Override
  public void onSensorChanged(SensorEvent event) {
    builder.setLength(0);
    builder.append("x: ");
    builder.append(event.values[0]);
    builder.append(", y: ");
    builder.append(event.values[1]);
    builder.append(", z: ");
    builder.append(event.values[2]);
    textView.setText(builder.toString());
  }

  @Override
  public void onAccuracyChanged(Sensor sensor, int accuracy) {

  }
}

   
    
    
  








Related examples in the same category

1.Using Sensor
2.Accelero meter Sensor
3.Compass sensor
4.Gravity sensor
5.Sensor.TYPE_GYROSCOPE
6.Light Sensor
7.PROXIMITY Sensor
8.Sensor List
9.Temperature Sensor
10.Sensor Changed event and information
11.Sensor Event Listener
12.Speed sensor
13.Sensor Test
14.Displays the values of the acceleration sensor graphically
15.Compass Activity
16.Using the accelerometer to integrate the device's acceleration to a position using the Verlet method.