Android如何设置传感器延迟?

Android how to set sensor delay?

对于我的项目,我创建了一个 class,它使用用户设备的传感器来检测北方。我只需要每秒更新一次,并希望通过延长延迟时间 节省一些电量 ,但我无法让延迟工作。我有什么:

mAcceleroSensor = mSensorManagerAccelero.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
mMagneticSensor = mSensorManagerMagnetic.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
// Tried to set normal values like SensorManager.SENSOR_DELAY_NORMAL
// and numbers like 100 - 100.000. 1.0000.0000 
// (without the dots only here to make it readable here).
mSensorManagerAccelero.registerListener(this, mAcceleroSensor, 50000000);
mSensorManagerMagnetic.registerListener(this, mMagneticSensor, 50000000);

一切正常,除了延迟,它几乎看起来像更新的实时。我使用了类似于 的代码,但做了一些小改动。

注意:我使用的最低api版本是14

SensorManager.registerListener(SensorEventListener listener, Sensor sensor, int samplingPeriodUs) 的文档:

The events will be delivered to the provided SensorEventListener as soon as they are available. To reduce the power consumption, applications can use registerListener(SensorEventListener, Sensor, int, int) instead and specify a positive non-zero maximum reporting latency.

虽然传感器的读数以给定的时间间隔进行采样,但未指定该方法中的报告时间间隔,导致一旦读数可用就会快速调用回调。使用文档中提到的替代方法:

 mSensorManagerAccelero.registerListener (this, mAcceleroSensor, 1000000, 1000000)

使其大约每秒报告一次(您可以根据需要手动调整采样率)。这也有助于用电。

注意文档声称最后一个参数 maxReportLatencyUs 是:

Maximum time in microseconds that events can be delayed before being reported to the application.

意味着它可能仍会比 1 秒更快地报告。如果您希望用户看到一致的平滑 1 秒更新,请考虑将结果保存到平均缓冲区并每秒更新一次 UI。