Class MotionSensorManager

java.lang.Object
com.codename1.sensors.MotionSensorManager

public abstract class MotionSensorManager extends Object

Cross platform access to the device motion sensors (accelerometer, gyroscope, magnetometer and the derived gravity, linear acceleration and orientation) together with high level gesture detection (shake, flip, tilt, pick up and free fall).

Obtain the singleton through getInstance(). The instance is always non null; on a device or port without motion sensors every sensor simply reports as unsupported and no events are delivered.

Reading a sensor
MotionSensorManager m = MotionSensorManager.getInstance();
MotionSensor accel = m.getSensor(MotionSensorManager.TYPE_ACCELEROMETER);
if (accel != null) {
    accel.addListener(new MotionSensorListener() {
        public void motionReceived(MotionEvent evt) {
            // evt.getX(), evt.getY(), evt.getZ() are in m/s^2
        }
    });
}
Listening for a gesture
MotionSensorManager.getInstance().addGestureListener(GestureEvent.TYPE_SHAKE, new GestureListener() {
    public void gestureDetected(GestureEvent evt) {
        Dialog.show("Shaken", "You shook the device", "OK", null);
    }
});

All callbacks are delivered on the EDT. Sampling is reference counted so the hardware sensors are only powered while at least one listener (sensor or gesture) is registered; remember to remove your listeners to save battery.

iOS note: access to the motion hardware requires the build argument ios.NSMotionUsageDescription describing why the app reads motion data.

  • Field Summary

    Fields
    Modifier and Type
    Field
    Description
    static final double
    Standard earth gravity in meters per second squared, the unit used by the acceleration sensors.
    static final int
    Accelerometer including the effect of gravity, in meters per second squared.
    static final int
    The gravity vector in meters per second squared.
    static final int
    Rate of rotation around the three axes in radians per second.
    static final int
    Acceleration with the effect of gravity removed, in meters per second squared.
    static final int
    The ambient magnetic field in microtesla.
    static final int
    Device orientation as azimuth, pitch and roll in radians.
  • Constructor Summary

    Constructors
    Constructor
    Description
     
  • Method Summary

    Modifier and Type
    Method
    Description
    void
    addGestureListener(int gestureType, GestureListener l)
    Registers a listener for a specific gesture.
    Returns the shared motion sensor manager.
    int
    The requested time between sensor samples in milliseconds.
    getSensor(int type)
    Returns the sensor object for the given type, or null if the type is not supported on this device.
    protected abstract boolean
    Whether the named hardware sensor is present on this device.
    boolean
    Whether the given sensor type can deliver readings on this device.
    protected abstract boolean
    readNativeSensor(int type, float[] out)
    Reads the latest value of the named hardware sensor.
    void
    Removes a previously registered gesture listener.
    void
    setFreeFallThreshold(double threshold)
    Sets the total acceleration, in meters per second squared, below which the device is considered to be in free fall.
    void
    setSamplingInterval(int millis)
    Sets the requested time between sensor samples in milliseconds.
    void
    setShakeThreshold(double threshold)
    Sets the linear acceleration spike, in meters per second squared, above which jolts are counted towards a shake.
    void
    setTiltThreshold(double radians)
    Sets the tilt angle, in radians, at which the tilt gestures fire.
    protected abstract void
    Starts the named hardware sensor.
    void
    Stops every sensor and removes all registered listeners.
    protected abstract void
    stopNativeSensor(int type)
    Stops the named hardware sensor.

    Methods inherited from class Object

    clone, equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
  • Field Details

    • TYPE_ACCELEROMETER

      public static final int TYPE_ACCELEROMETER
      Accelerometer including the effect of gravity, in meters per second squared.
      See Also:
    • TYPE_LINEAR_ACCELERATION

      public static final int TYPE_LINEAR_ACCELERATION
      Acceleration with the effect of gravity removed, in meters per second squared. Derived in the core from the accelerometer when the platform does not provide it natively.
      See Also:
    • TYPE_GRAVITY

      public static final int TYPE_GRAVITY
      The gravity vector in meters per second squared. Derived in the core from the accelerometer when the platform does not provide it natively.
      See Also:
    • TYPE_GYROSCOPE

      public static final int TYPE_GYROSCOPE
      Rate of rotation around the three axes in radians per second.
      See Also:
    • TYPE_MAGNETOMETER

      public static final int TYPE_MAGNETOMETER
      The ambient magnetic field in microtesla.
      See Also:
    • TYPE_ORIENTATION

      public static final int TYPE_ORIENTATION
      Device orientation as azimuth, pitch and roll in radians. Derived in the core from the gravity vector (and the magnetometer for the azimuth).
      See Also:
    • STANDARD_GRAVITY

      public static final double STANDARD_GRAVITY
      Standard earth gravity in meters per second squared, the unit used by the acceleration sensors.
      See Also:
  • Constructor Details

    • MotionSensorManager

      public MotionSensorManager()
  • Method Details

    • getInstance

      public static MotionSensorManager getInstance()
      Returns the shared motion sensor manager. Never null: when the active port does not provide motion sensors a no-op manager is returned whose sensors all report as unsupported.
    • isNativeSensorSupported

      protected abstract boolean isNativeSensorSupported(int type)

      Whether the named hardware sensor is present on this device. Only the hardware backed types (TYPE_ACCELEROMETER, TYPE_GYROSCOPE, TYPE_MAGNETOMETER and, where the OS exposes them, TYPE_GRAVITY and TYPE_LINEAR_ACCELERATION) are queried here; derived types are resolved by isSensorSupported(int).

      Parameters
      • type: one of the TYPE_* constants
    • startNativeSensor

      protected abstract void startNativeSensor(int type)
      Starts the named hardware sensor. Called when the first listener that needs it is registered.
    • stopNativeSensor

      protected abstract void stopNativeSensor(int type)
      Stops the named hardware sensor. Called when the last listener that needed it is removed.
    • readNativeSensor

      protected abstract boolean readNativeSensor(int type, float[] out)

      Reads the latest value of the named hardware sensor.

      Parameters
      • type: one of the TYPE_* constants
      • out: a three element array to receive the x, y and z values
      Returns

      true if a value was written, false if no reading is available yet

    • isSensorSupported

      public boolean isSensorSupported(int type)

      Whether the given sensor type can deliver readings on this device. Takes into account values that the core derives from other sensors, so for example TYPE_ORIENTATION is supported whenever the accelerometer is.

      Parameters
      • type: one of the TYPE_* constants
    • getSensor

      public MotionSensor getSensor(int type)

      Returns the sensor object for the given type, or null if the type is not supported on this device. The same instance is returned for repeated calls with the same type.

      Parameters
      • type: one of the TYPE_* constants
    • addGestureListener

      public void addGestureListener(int gestureType, GestureListener l)

      Registers a listener for a specific gesture. The accelerometer is powered automatically while at least one gesture listener is registered.

      Parameters
      • gestureType: one of the GestureEvent.TYPE_* constants
      • l: the listener to invoke when the gesture occurs
    • removeGestureListener

      public void removeGestureListener(int gestureType, GestureListener l)

      Removes a previously registered gesture listener.

      Parameters
      • gestureType: the gesture the listener was registered for
      • l: the listener to remove
    • getSamplingInterval

      public int getSamplingInterval()
      The requested time between sensor samples in milliseconds. Defaults to 50ms (20Hz). The actual rate the hardware delivers may differ.
    • setSamplingInterval

      public void setSamplingInterval(int millis)

      Sets the requested time between sensor samples in milliseconds. Smaller values give more responsive gestures at a higher battery cost. Values are clamped to the range 10ms..1000ms.

      Parameters
      • millis: the requested interval
    • setShakeThreshold

      public void setShakeThreshold(double threshold)
      Sets the linear acceleration spike, in meters per second squared, above which jolts are counted towards a shake. Larger values require a more vigorous shake. The default is 12.0.
    • setTiltThreshold

      public void setTiltThreshold(double radians)
      Sets the tilt angle, in radians, at which the tilt gestures fire. The default is roughly 0.6 (about 34 degrees).
    • setFreeFallThreshold

      public void setFreeFallThreshold(double threshold)
      Sets the total acceleration, in meters per second squared, below which the device is considered to be in free fall. The default is 3.0.
    • stop

      public void stop()
      Stops every sensor and removes all registered listeners. Mostly useful for tests and for an explicit shutdown.