Search code examples
androidaccelerometershake

Shaking phone direction


Is there any way to detect to which direction the phone was shaked? For example: I want something be shot from the right border of the screen, so I need to look if a phone was shaked to the left (coordinates from the beginning of first movement). And nearly the same for the left border. Hope you understand.

Thanks a lot!


Solution

  • You can detect the change in a specific direction by implementing SensorEventListener and checking:

    public void onSensorChanged(SensorEvent se) {
        // Get sensor data.
        float x = se.values[SensorManager.DATA_X];
        float y = se.values[SensorManager.DATA_Y];
        float z = se.values[SensorManager.DATA_Z];
    }
    

    Then simply compare a few consecutive values of one of the variables to determine the direction. I think that X is the one you're interested in.