Being the type that likes to encapsulate things and make them reusable later down the line I thought wouldn't it be neat if this snippet say inside it's own listener that I could just implement in my activities? So I put this together and thought I'd share it with the folks here:
ShakeListener.java
Using java Syntax Highlighting
- import java.util.List;
- import android.hardware.Sensor;
- import android.hardware.SensorEvent;
- import android.hardware.SensorEventListener;
- import android.hardware.SensorManager;
- public class ShakeListener implements SensorEventListener{
- private static final String TAG = "ShakeListener";
- private OnShakeListener mOnShakeListener = null;
- private SensorManager mSensorManager;
- private double mTotalForcePrev; // stores the previous total force value
- private double mForceThreshHold = 1.5f;
- private List<Sensor> mSensors;
- private Sensor mAccelerationSensor;
- public ShakeListener(SensorManager sm){
- mSensorManager = sm;
- mSensors = mSensorManager.getSensorList(Sensor.TYPE_ACCELEROMETER);
- if(mSensors.size() > 0) {
- mAccelerationSensor = mSensors.get(0);
- mSensorManager.registerListener(this, mAccelerationSensor, SensorManager.SENSOR_DELAY_GAME);
- }
- }
- public void setForceThreshHold(double threshhold){
- mForceThreshHold = threshhold;
- }
- public double getForceThreshHold(){
- return mForceThreshHold;
- }
- public void onAccuracyChanged(Sensor sensor, int accuracy) {}
- public void onSensorChanged(SensorEvent event) {
- double totalForce = 0.0f;
- totalForce += Math.pow(event.values[0]/SensorManager.GRAVITY_EARTH, 2.0);
- totalForce += Math.pow(event.values[1]/SensorManager.GRAVITY_EARTH, 2.0);
- totalForce += Math.pow(event.values[2]/SensorManager.GRAVITY_EARTH, 2.0);
- totalForce = Math.sqrt(totalForce);
- if((totalForce < mForceThreshHold) && (mTotalForcePrev > mForceThreshHold)) {
- OnShake(); // raise the onShake event.
- }
- mTotalForcePrev = totalForce;
- }
- public void setOnShakeListener(OnShakeListener listener) {
- mOnShakeListener = listener;
- }
- private void OnShake(){
- if(mOnShakeListener!=null) {
- mOnShakeListener.onShake();
- }
- }
- public interface OnShakeListener {
- public abstract void onShake();
- }
- }
Parsed in 0.038 seconds, using GeSHi 1.0.8.4
And to implement it in an Activity just use the following:
Using java Syntax Highlighting
- ShakeListener MyShake = new ShakeListener((SensorManager) getSystemService(SENSOR_SERVICE));
- MyShake.setForceThreshHold(1.9);
- MyShake.setOnShakeListener(new ShakeListener.OnShakeListener() {
- @Override
- public void onShake() {
- mPad.Clear();
- }
- });
Parsed in 0.030 seconds, using GeSHi 1.0.8.4
You can use MyShake.setForceThreshHold(1.9) to set the sensitivity of the shake.
Enjoy,
-TM
EDIT: Updated for API Level 3.

