The bottom line is this: the device reads information about the accelerometer sensors, and if the user starts shaking the phone, the application signals this.

I understand that, in principle, this is an easy task, but I just can not figure out how to write this unfortunate code.

  • 3
    Hands? To dictate? The specific question is what? How to get data from the accelerometer? How to process them? How to signal? How to determine that the accelerometer data correspond to the parameters of shaking? - Chad
  • If you dictate, I will be grateful. Specific questions - "how to get data from the accelerometer?" and "how to process them?". How to signal - I'll think of it myself. Answering the last question, the main thing is that they (the shaking parameters) were, you can already calibrate yourself. Link see, thank you so much. - veselllov

1 answer 1

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.