Android Tutorial: Implement A Shake Listener

So I’ve been playing around with Android and have a little app that I wanted the user to be able to shake the phone and have something happen. I did some digging and the following is a tutorial on how to setup a shake listener to capture a shake and then do whatever you want.

This is by no means something that I’ve created, I just used examples that I found on stackoverflow.com. Also, this uses G-force to calculate the shake threshold. Many thanks to Peterdk and Akos Cz for their input and answer for this solution. Peterdk recommended using the G-Force app by Blake La Pierre on Google Play Store if you want to get the actual G-force value on your phone and tweak it in the code below.

Long story short, there are 5 things that need to happen to get this to work:

  1. Create a new class named ShakeDetector
  2. Define variables for sensor manager, shake detector and accelerometer
  3. Add/register the sensor manager and listener in the onCreate() method in your activity
  4. Configure onResume and onPause to activate/deactivate the accelerometer
  5. Edit the AndroidManifest.xml file to require the device to have an accelerometer

Here’s how to do it all:

Step 1

Create a new class named ShakeDetector and put the following code in it:

I get a warning in Eclipse about the sqrt on line 50 of the code above saying “Use java.lang.Math#sqrt instead of android.util.FloatMath#sqrt() since it is faster as of API 8”, but I choose to ignore it.

Step 2

At the beginning of your activity, declare the following variables:

Step 3

Now, in your activity, paste the following in the onCreate() method:

Take care of any missing import statements (ctrl+shift+o in Eclipse). Create your own handleShakeEvent method to do what you want when a shake is detected. Or, remove the stub reference to handleShakeEvent(count); in the code above and create your own method or add what you want in its place.

Step 4

Modify (or add) onResume and onPause to include the following line:

Step 5

I also added the following in my AndroidManifest.xml to make sure the phone has an accelerometer (it goes right after the <uses-sdk /> section):

There you have it. I hope this helps!

Sources:

2 Comments

  1. Thanx a lot. Very useful code. I just added thread to accumulate the number of shakes to work with a sum of shakes not a series.

  2. FloatMath deprecated. replaced w/

    float gForce = (float)Math.sqrt( gX * gX + gY * gY + gZ * gZ );

Leave a Reply

© 2017 Jason McReynolds

Theme by Anders NorénUp ↑