Skip to content

Instantly share code, notes, and snippets.

@MiraLak MiraLak/AccelerometerActivity.java Secret
Last active Aug 29, 2015

Embed
What would you like to do?
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
You can’t perform that action at this time.