I need to add a shake feature that will refresh my Android application.
All I find of documentation involves implementing the SensorListener
, but Eclipse tells me it's deprecated and suggest SensorEventListener
.
Anybody that has a nice guide to how I go about creating this shake controller
?
Here is an example code. Put this into your activity class:
And add this to your onCreate method:
You can then ask "mAccel" wherever you want in your application for the current acceleration, independent from the axis and cleaned from static acceleration such as gravity. It will be approx. 0 if there is no movement, and, lets say >2 if the device is shaked.
Based on the comments - to test this:
Notes:
The accelometer should be deactivated onPause and activated onResume to save resources (CPU, Battery). The code assumes we are on planet Earth ;-) and initializes the acceleration to earth gravity. Otherwise you would get a strong "shake" when the application starts and "hits" the ground from free-fall. However, the code gets used to the gravitation due to the low-cut filter and would work also on other planets or in free space, once it is initialized. (you never know how long your application will be in use...;-)
Here is another code for this:
Working with me v.good Reference
I really liked Peterdk's answer. I took it upon myself to make a coulpe of tweaks to his code .
file: ShakeDetector.java
Also, don't forget that you need to register an instance of the ShakeDetector with the SensorManager.