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:
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 forTYPE_ACCELEROMETER
in thegetDefaultSensor()
method ofSensorManager
and initiate theMediaPlayer
object with the audio MP3 file kept in the raw folder inside theonCreate()
method of the activity. As a standard practice, we will register the listener inonResume()
and un-register it in...