MotionDetector.kt
| 1 | package org.opentracker |
| 2 | |
| 3 | import android.content.Context |
| 4 | import android.hardware.Sensor |
| 5 | import android.hardware.SensorManager |
| 6 | import android.hardware.TriggerEvent |
| 7 | import android.hardware.TriggerEventListener |
| 8 | |
| 9 | /** |
| 10 | * The significant-motion sensor. It runs in the sensor hub, not on the CPU, which makes |
| 11 | * turning GNSS off in STATIONARY safe. The callback comes on a sensor thread. |
| 12 | */ |
| 13 | class MotionDetector(context: Context, private val onMotion: () -> Unit) { |
| 14 | private val sm = context.getSystemService(SensorManager::class.java) |
| 15 | private val sensor: Sensor? = sm.getDefaultSensor(Sensor.TYPE_SIGNIFICANT_MOTION) |
| 16 | private val listener = object : TriggerEventListener() { |
| 17 | override fun onTrigger(event: TriggerEvent?) = onMotion() |
| 18 | } |
| 19 | |
| 20 | /** The sensor is one-shot: it cancels itself when it fires, so arm it again after each trigger. */ |
| 21 | fun arm() { |
| 22 | sensor ?: return |
| 23 | sm.cancelTriggerSensor(listener, sensor) |
| 24 | sm.requestTriggerSensor(listener, sensor) |
| 25 | } |
| 26 | |
| 27 | fun disarm() { |
| 28 | sensor?.let { sm.cancelTriggerSensor(listener, it) } |
| 29 | } |
| 30 | } |
| 31 |