如何将传感器数据采样率延迟到一秒?

How to delay sensor data sample rate to one second?

我目前正在使用 AsyncTask 将来自各种传感器(加速度计、陀螺仪等)的数据发送到数据库。

一旦 onSensorChanged 被触发,我就会为每个传感器提供每项服务,通过广播将数据发送回 mainActivity。

问题是传感器数据变化太快以至于数据库在几秒钟内就被淹没了。 我想要的是每秒触发一次onSensorChanged方法,但是通过1秒(1*10^6 us)的采样周期根本没有任何效果。

有没有其他方法可以实现 1 秒延迟?

强烈建议查看响应式框架,RxJava in particular (there's RxKotlin as well). Once you get used to it, it will greatly improve quality of code and robustness on i/o tasks. It supports desired behavior out of the box (debounce operator)

来自开发者网站

The data delay (or sampling rate) controls the interval at which sensor events are sent to your application via the onSensorChanged() callback method. The default data delay is suitable for monitoring typical screen orientation changes and uses a delay of 200,000 microseconds. You can specify other data delays, such as SENSOR_DELAY_GAME (20,000 microsecond delay), SENSOR_DELAY_UI (60,000 microsecond delay), or SENSOR_DELAY_FASTEST (0 microsecond delay). As of Android 3.0 (API Level 11) you can also specify the delay as an absolute value (in microseconds)

The delay that you specify is only a suggested delay. The Android system and other applications can alter this delay. As a best practice, you should specify the largest delay that you can because the system typically uses a smaller delay than the one you specify (that is, you should choose the slowest sampling rate that still meets the needs of your application). Using a larger delay imposes a lower load on the processor and therefore uses less power.

There is no public method for determining the rate at which the sensor framework is sending sensor events to your application; however, you can use the timestamps that are associated with each sensor event to calculate the sampling rate over several events. You should not have to change the sampling rate (delay) once you set it. If for some reason you do need to change the delay, you will have to unregister and reregister the sensor listener.

希望这对您有所帮助。您可以使用额外的服务/后台线程,以便在数据库插入方法之前实现准确的时间延迟。