如何每秒从 Android 内置加速度计中读取一次?

How to read only once from Android build in Accelerometer per second?

在 sensorManager 的帮助下,我正在读取加速度计读数。目前最慢的设置即 SENSOR_DELEY_NORMAL ,加速度计每秒读取大约 10 次。有什么办法可以减少发送读数,可能是每秒一次。

 @Override
    public void onSensorChanged(SensorEvent sensorEvent) {
        Sensor mySensor = sensorEvent.sensor;

        if (mySensor.getType() == Sensor.TYPE_ACCELEROMETER) {
            x = sensorEvent.values[0];
            y = sensorEvent.values[1];
            z = sensorEvent.values[2];
            rootSquare = Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2) + Math.pow(z, 2));
            
            //it reads every second 10 times ie 200 millisecon
}


 @Override
    protected void onResume() {
        super.onResume();

    sensorManager.registerListener(this, accelorometer, SensorManager.SENSOR_DELAY_NORMAL);

    }

基于此answer,您还可以定义自己的速率,例如 1000 ms = 1s:

 @Override
    public void onSensorChanged(SensorEvent sensorEvent) {
        Sensor mySensor = sensorEvent.sensor;

        if (mySensor.getType() == Sensor.TYPE_ACCELEROMETER) {
            x = sensorEvent.values[0];
            y = sensorEvent.values[1];
            z = sensorEvent.values[2];
            rootSquare = Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2) + Math.pow(z, 2));
            
            //it reads every second 10 times ie 200 millisecon
}


 @Override
    protected void onResume() {
        super.onResume();

    int READINGRATE_ONE_SEC = 1000000;
    sensorManager.registerListener(this, accelorometer, READINGRATE_ONE_SEC);

    }