2

I'm having a hard time finding this out properly. All I want is that when I shake my color changes to something else or text changes to something. Doesn't have to be random tho. Can't find anything usefull that doesn't include useless stuff.

PrivateerGerrit
  • 227
  • 6
  • 17

2 Answers2

2

Not even 20 seconds of googling gives you already a probably perfectly fine working copy-paste solution with an easy call-back where you can do anything you want inside your Activity...

http://android.hlidskialf.com/blog/code/android-shake-detection-listener

Stefan de Bruijn
  • 6,159
  • 2
  • 18
  • 29
0

Use the below class and when creating a new instance of it call the setCallBack method on that instance you created to receive callbacks ,pass that instance when you register a listener through the sensor manager.

import android.hardware.Sensor;

import android.hardware.SensorEvent;

import android.hardware.SensorEventListener;



public class ShakeListener implements SensorEventListener {

    private ShakeCallback mShakeCallback;

    private int totalMovement;
    private long timeMilies;
    private float lastX, lastY, lastZ = -1.0f;
    private int shakeIntervalMilies = 2000;

    ShakeListener() {
    }

    public static ShakeListener newInstance() {
        return new ShakeListener();
    }


    public ShakeListener setCallBack(ShakeCallback shakeCallback) {
        this.mShakeCallback = shakeCallback;

        return this;
    }


    public ShakeListener setShakingInterval(int intervalMilies) {
        this.shakeIntervalMilies = intervalMilies;

        return this;
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        if (mShakeCallback != null) {
            totalMovement = (int) ((event.values[0] + event.values[1] + event.values[2]) - (lastX
                    + lastY + lastZ));
            if (totalMovement > 20
                    && (System.currentTimeMillis() - timeMilies >= shakeIntervalMilies)) {
                mShakeCallback.onShake();
                timeMilies = System.currentTimeMillis();

            }
            lastX = event.values[0];
            lastY = event.values[1];
            lastZ = event.values[2];
        }
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {

    }
    public static interface ShakeCallback {
        public void onShake();

    }

}
shobhan
  • 1,260
  • 2
  • 12
  • 27
user1283633
  • 1,135
  • 1
  • 13
  • 22