ShakeDetector

class ShakeDetector(sensorManager: SensorManager?, threshold: Float = DEFAULT_THRESHOLD_G, minimumShakes: Int = DEFAULT_MINIMUM_SHAKES, minimumDurationMillis: Long = DEFAULT_MINIMUM_DURATION_MILLIS, cooldownMillis: Long = DEFAULT_COOLDOWN_MILLIS, elapsedRealtime: () -> Long = SystemClock::elapsedRealtime, onShake: () -> Unit) : SensorEventListener(source)

Reports a deliberate, repeated shake of the device.

A shake is counted each time the acceleration rises above threshold after settling back towards rest, which is what every direction reversal of a hand shaking the phone produces; a back-and-forth is two. A reading must fall below the midpoint between rest and threshold before the next rise counts, so a reading that hovers around threshold stays one shake.

Three guards separate the gesture from ordinary handling, and all three are needed. A single jolt, which is what putting a phone down on a table produces, is one or two shakes, so the gesture needs minimumShakes of them, spread across at least minimumDurationMillis, within a rolling window that forgets a half-finished gesture. cooldownMillis then keeps one gesture from reporting several times as it decays.

The defaults ask for about three firm back-and-forth shakes over most of a second, so the sheet never opens from a phone being handled, pocketed or put down; they are constructor parameters so they can be tuned against real devices without touching this logic.

Nothing is registered until start, and stop leaves no listener behind. The detector reads acceleration only, which needs no runtime permission.

Parameters

sensorManager

Platform sensor service, null on a device that does not expose one.

threshold

Acceleration counted as shaking, as a multiple of gravity. Must exceed 1, the resting reading.

minimumShakes

Shakes the gesture needs before it is reported.

minimumDurationMillis

How long the gesture must last before it counts.

cooldownMillis

Quiet period after a reported shake.

elapsedRealtime

Monotonic clock, replaceable in tests.

onShake

Invoked on the main thread, which is where sensor callbacks are delivered.

Constructors

Link copied to clipboard
constructor(sensorManager: SensorManager?, threshold: Float = DEFAULT_THRESHOLD_G, minimumShakes: Int = DEFAULT_MINIMUM_SHAKES, minimumDurationMillis: Long = DEFAULT_MINIMUM_DURATION_MILLIS, cooldownMillis: Long = DEFAULT_COOLDOWN_MILLIS, elapsedRealtime: () -> Long = SystemClock::elapsedRealtime, onShake: () -> Unit)

Types

Link copied to clipboard
object Companion

Functions

Link copied to clipboard
open override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int)
Link copied to clipboard
open override fun onSensorChanged(event: SensorEvent?)
Link copied to clipboard
fun start(): Boolean

Registers for accelerometer updates.

Link copied to clipboard
fun stop()

Unregisters the listener.