Hi everyone. I meet issue. how to detect when the ...
# compose-wear
l
Hi everyone. I meet issue. how to detect when the user is not wearing their WearOS device?
l
I think you can look into the sensors that sensorManager will give you (through code, some sensors are not documented)
l
Copy code
class WearDetectionService : Service(), SensorEventListener {

    private lateinit var sensorManager: SensorManager
    private var heartRateSensor: Sensor? = null
    private var job: Job? = null

    companion object {
        val isWorn = MutableLiveData(true)
    }

    override fun onCreate() {
        super.onCreate()
        sensorManager = getSystemService(Context.SENSOR_SERVICE) as SensorManager
        heartRateSensor = sensorManager.getDefaultSensor(Sensor.TYPE_HEART_RATE)
        sensorManager.registerListener(this, heartRateSensor, SensorManager.SENSOR_DELAY_NORMAL)
    }

    override fun onDestroy() {
        super.onDestroy()
        sensorManager.unregisterListener(this)
        job?.cancel()
    }

    override fun onBind(intent: Intent?): IBinder? {
        return null
    }

    override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {}

    override fun onSensorChanged(event: SensorEvent?) {
        if (event?.sensor?.type == Sensor.TYPE_HEART_RATE) {
            job?.cancel()
            isWorn.postValue(true)
            job = CoroutineScope(Dispatchers.Default).launch {
                delay(10000) // 10 seconds without heart rate data
                isWorn.postValue(false)
            }
        }
    }
}
i will try it, but not working for me.
l
Don't use a Service
The sensor is not heart_rate BTW
It's another type. Just look into getSensors(TYPE_ALL), log/print it, and there should be one specific to the "worn/not-worn".
What's your use case BTW? You don't need it to work while in the background, do you?
l
currently app is running background
l
What's your use case?
l
I am developing a wear app, and record heart rate from wear, then send to phone. I want to detect when user takes off wear? to automatically close the app.
l
Do you want to record the heart rate non-stop, or only for a limited duration, after the user starts an action?
l
I have a workout maybe 10-20 minutes or 2-3 hours. We will record heart rate.
l
Did you find the sensor that detects the on_body status?
l
i will double check it. Thank you.
l
currently, i use api health, I use solution, check heart rate = 0 in 10 seconds, I will count as not wearing watch. It work ok, but I want to check if the sensor support is 100%?
a
The sensor is the offbody detector. The constant in the SDK is TYPE_LOW_LATENCY_OFFBODY_DETECT (or TYPE_STRING_LOW_LATENCY_OFFBODY_DETECT).
Samsung have a developer blog post on it here which looks correcgt
The latency should be around 3 seconds max
l
oh, i fixed issue, thank you all.