Leveraging Sensor batching

1.5k views Asked by At

I'm trying to utilize the max fifo size of Accelerometer on Nexus 6

SensorManager sensorManager =
                (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        Sensor sensor = sensorManager.getDefaultSensor(typeAccelerometer);
        Log.e("test",
                "Max delay: " + sensor.getMaxDelay() + " - Fifo count" + sensor.getFifoReservedEventCount()); // prints 1000000 (1 second) - Fifo count 10000

        // Register the listener for this sensor in batch mode.
        // Following code reports every 190ms when screen is ON, and every 10 seconds when screen is OFF. I always want every 10 seconds.
        final boolean batchMode = sensorManager.registerListener(
            mListener, sensor, 1000000 /* 1 second */, 10000000 /* 10 seconds */);

private final SensorEventListener mListener = new SensorEventListener() {
    long lastTimeStamp;
    @Override
    public void onSensorChanged(SensorEvent event) {
        long current = System.currentTimeMillis();
         long time =  current - lastTimeStamp;

        if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
            Log.e("test",
                    "New ACCELERO "+ " -> "+ time + "ms -> " + (int)event.values[0] + " -> "+ (int)event.values[1] +" -> "+ (int)event.values[2]);
            lastTimeStamp = current;
        }
    }

    @Override
    public void onAccuracyChanged(Sensor s, int accuracy) {

    }
};

When Screen is ON, I get the events every 190ms. However, when screen is off, it obeys 10 seconds.

How do I utilize the full batching FIFO (with delayed listeners) when screen is ON, for minimal CPU impact.

3

There are 3 answers

0
Taranfx On

Code above is fine. On Nexus 6, accelerometer doesnt batch as long as screen is ON. All other sensors do fine.

1
Caerbannog On

Beware of the third argument to registerListener. It is not in seconds like you wrote:

 final boolean batchMode = sensorManager.registerListener(
            mListener, sensor, 1000000 /* WRONG */, 10000000);

It should be one of the following constants:

  • SENSOR_DELAY_NORMAL
  • SENSOR_DELAY_UI
  • SENSOR_DELAY_GAME
  • SENSOR_DELAY_FASTEST.

Source: https://developer.android.com/reference/android/hardware/SensorManager.html#registerListener(android.hardware.SensorEventListener,%20android.hardware.Sensor,%20int,%20int)

0
ssk360 On

sensor.getFifoReservedEventCount() returns the amount of values it can store, i dont think its time in ms