androidhandlerwear-ospostdelayed

How to get heart rate every x seconds in Android Studio?


I want to get data from the Heart Rate sensor every x seconds. I tried it with postDelayed() but that only works for reading the data every x seconds, but the sensor is running in that time and the battery drains very fast. I'm trying to find a way to start the sensor, get the data and stop the sensor every x seconds.

Here's what I did so far:

final Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            checkHR = true;
            handler.postDelayed(this, 10000);
        }
    }, 1);

public void onSensorChanged(SensorEvent event) {
    if(checkHR == true){
        if (event.sensor.getType() == Sensor.TYPE_HEART_RATE) {
            String msg = "" + (int)event.values[0];
            heartRate = (int)event.values[0];
            Log.d("Heart rate is:", msg);
            checkHR = false;
        }
    }

Solution

  • have you tried to unregisterListener after obtaining some data in onSensorChanged? and register again when postDelayed fire. maybe thats why sensor is still working (still registered sensor, even when checkHR=false) and draining your battery. can you show how do you register this listener? heart monitor isn't so common in Android devices...

    with default sensors implementation (SensorManager and SensorEventListener) this is only possible way to disable sensor - in fact system is handling sensors whole the time and only pass data when some app is registering listener. So there is a chance that when you unregister your listener and no other app will have registered similar listener then system will disable sensor by default, as no one request data from it...