Here is a simple example of obtaining accelerometer data: if you change at least one coordinate to the mOffset value, the current coordinate values are displayed in the TextView :
public class MainActivity extends AppCompatActivity implements SensorEventListener { private TextView mTextView; private SensorManager mSensorManager; private Sensor mAccelerometer; private double mX, mY, mZ; private final double mOffset = 0.1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mTextView = (TextView) findViewById(R.id.text_view); mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL); } @Override public void onSensorChanged(SensorEvent event) { Sensor mySensor = event.sensor; if (mySensor.getType() == Sensor.TYPE_ACCELEROMETER) { float x = event.values[0]; float y = event.values[1]; float z = event.values[2]; if (Math.abs(x - mX) >= mOffset || Math.abs(y - mY) >= mOffset || Math.abs(z - mZ) >= mOffset) { mTextView.setText("x = " + x + "\ny = " + y + "\nz = " + z); mX = x; mY = y; mZ = z; } } } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { } protected void onResume() { super.onResume(); mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL); } protected void onPause() { super.onPause(); mSensorManager.unregisterListener(this); } }
To determine the shaking, you can measure the change of coordinates for certain time intervals. If for some ( small ) period of time there was a change of coordinates to some particular delta, then there was a shaking .
The above is, of course, the most primitive case.