利用传感器批处理

时间:2015-06-07 13:35:41

标签: android android-sensors

我试图在Nexus 6上使用最大fifo尺寸的Accelerometer

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) {

    }
};

当屏幕开启时,我每隔190ms就会收到一次事件。但是,当屏幕关闭时,它会服从10秒钟。

当屏幕打开时,如何利用完整的批处理FIFO(具有延迟的侦听器),以最大限度地减少CPU的影响。

3 个答案:

答案 0 :(得分:0)

上面的代码很好。在Nexus 6上,只要屏幕打开,加速计就不会批量生产。所有其他传感器都可以。

答案 1 :(得分:0)

注意registerListener的第三个参数。它不像你写的那样在几秒钟内完成:

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

它应该是以下常量之一:

  • SENSOR_DELAY_NORMAL
  • SENSOR_DELAY_UI
  • SENSOR_DELAY_GAME
  • SENSOR_DELAY_FASTEST。

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

答案 2 :(得分:-1)

sensor.getFifoReservedEventCount()返回它可以存储的值的数量,我不认为它的时间以毫秒为单位