Time for action – shake detection using the accelerometer sensor

One of the most common use cases of the accelerometer sensor is to detect the shaking of the phone. Shaking can act as a valuable input for the apps, especially when the phone screen is off. For example, a lot of music player apps allow you to change the songs just by shaking the phone. In our example, we will play a small audio MP3 file when the phone shake is detected using the accelerometer sensor:

  1. As the first step, we create the necessary infrastructure to get the values from the accelerometer sensor. We will create a ShakeDetectionActivity and follow the standard steps for getting values from a sensor. We will select the sensor type for TYPE_ACCELEROMETER in the getDefaultSensor() method of SensorManager and initiate the MediaPlayer object with the audio MP3 file kept in the raw folder inside the onCreate() method of the activity. As a standard practice, we will register the listener in onResume()and un-register it in the onPause() methods:

            public class ShakeDetectionActivity extends Activity implements 
            SensorEventListener { 
     
              private SensorManager mSensorManager; 
              private Sensor mAccelerometer; 
              private float x,y,z,last_x,last_y,last_z; 
              private boolean isFirstValue; 
              private float shakeThreshold = 3f; 
              private MediaPlayer mMediaPlayer; 
     
              @Override 
              protected void onCreate(Bundle savedInstanceState) { 
                super.onCreate(savedInstanceState); 
                setContentView(R.layout.shakedetection_layout); 
                mSensorManager = (SensorManager)getSystemService
                (SENSOR_SERVICE); 
                mAccelerometer = mSensorManager.getDefaultSensor
                (Sensor.TYPE_ACCELEROMETER); 
                mMediaPlayer = MediaPlayer.create(getApplicationContext(), 
                R.raw.mario); 
              } 
     
              protected void onResume() { 
                super.onResume(); 
                mSensorManager.registerListener(this, mAccelerometer, 
                SensorManager.SENSOR_DELAY_UI); 
              } 
     
              protected void onPause() { 
                super.onPause(); 
                mSensorManager.unregisterListener(this, mAccelerometer); 
              } 
            } 
    
  2. Inside the onSensorChanged() method, we write our core logic to detect shakes. When we shake the phone with our hands, the accelerometer sensor measures the force acting on the phone. There is a huge variation in the force acting on the phone during the shake. We measure this variation or change in the acceleration. If the change in acceleration in any two axes crosses a threshold of 3 m/s2, then we consider it a shake. The threshold of 3 m/s2 can only be reached by shaking the phone with the hands. To calculate the change in acceleration, we take the absolute difference between the current and last known accelerometer values, and if the absolute difference is greaten than 3m/s2  in any two axes, then we play the sound:

            @Override 
            public void onSensorChanged(SensorEvent event) { 
     
              x = event.values[0]; 
              y = event.values[1]; 
              z = event.values[2]; 
              if(isFirstValue) { 
                float deltaX = Math.abs(last_x - x); 
                float deltaY = Math.abs(last_y - y); 
                float deltaZ = Math.abs(last_z - z); 
                // If the values of acceleration have changed on at least two 
                axes, then we assume that we are in a shake motion 
                if((deltaX > shakeThreshold && deltaY > shakeThreshold)
                || (deltaX > shakeThreshold && deltaZ > shakeThreshold) 
                || (deltaY > shakeThreshold && deltaZ > shakeThreshold)) { 
                  //Don't play sound, if it is already being played 
                  if(!mMediaPlayer.isPlaying()) { 
                    //Play the sound, when Phone is Shaking 
                    mMediaPlayer.start(); 
                  } 
               } 
             } 
             last_x = x; 
             last_y = y; 
             last_z = z; 
             isFirstValue = true; 
           } 
    
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset