Skip to content

Instantly share code, notes, and snippets.

@MiraLak
Last active August 29, 2015 14:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MiraLak/cd7832d742d530598754 to your computer and use it in GitHub Desktop.
Save MiraLak/cd7832d742d530598754 to your computer and use it in GitHub Desktop.
Android app: Basic accelerometer
public class AccelerometerActivity extends ActionBarActivity implements SensorEventListener{
//...
private TextView acceleration;
private SensorManager sm;
private Sensor accelerometer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_accelerometer);
//get sensor manager service and init accelerometer sensor already existing
sm = (SensorManager) getSystemService(SENSOR_SERVICE);
accelerometer = sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
startSensor();
//get acceleration values shown on screen
acceleration = (TextView) findViewById(R.id.acceleration);
//...
// added button to stop sensor and quit the app
Button myButton = (Button) findViewById(R.id.button_exit);
myButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
stopSensor();
finish();
}
});
}
@Override
protected void onResume() {
super.onResume();
startSensor();
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
//Do nothing
}
@Override
public void onSensorChanged(SensorEvent event) {
//every time the sensor captures an event, the view is updated with the new values
Acceleration capturedAcceleration = getAccelerationFromSensor(event);
updateTextView(capturedAcceleration);
//...
}
private void updateTextView(Acceleration capturedAcceleration) {
acceleration.setText("X:" + capturedAcceleration.getX() +
"\nY:" + capturedAcceleration.getY() +
"\nZ:" + capturedAcceleration.getZ() +
"\nTimestamp:" + capturedAcceleration.getTimestamp());
}
private void startSensor() {
sm.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_NORMAL);
}
private void stopSensor() {
sm.unregisterListener(this);
}
private Acceleration getAccelerationFromSensor(SensorEvent event) {
//format timestamp
long timestamp = (new Date()).getTime() + (event.timestamp - System.nanoTime()) / 1000000L;
//create a new acceleration bean with X,Y and Z axes values and timestamp
return new Acceleration(event.values[0], event.values[1], event.values[2], timestamp);
}
//...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment