简体   繁体   中英

How to slow down android sensor events

I'm trying to detect motion of an android device and taking linear acceleration values from the device. I'm using the SensorEvent's timestamp and comparing it against the last update time to determine whether to log the sensor value or not. But it's having no effect whatsoever. Why isn't it working?

@Override
public void onSensorChanged(SensorEvent event) {
    if(event.sensor.getType() == Sensor.TYPE_LINEAR_ACCELERATION) {

            int value = (int) event.values[0];
            if(actualTime - lastUpdate > 5000) {
                Log.d(TAG, "" + value);
                lastUpdate = actualTime;
            }

If you want to change the rate to access the sensors, you can specify the frequency in the registerListener, as in the official documentation.

@Override
protected void onResume() {
    super.onResume();
    mSensorManager.registerListener(this, mLight,SensorManager.SENSOR_DELAY_NORMAL);
}

In this example, the default data delay (SENSOR_DELAY_NORMAL) is specified when the registerListener() method is invoked. 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).

It's definitely possible to slow it down :)

It's hard to tell from your code if your logic is correct, but a possible reason is that the Sensor timestamp is in nanoseconds.

See documentation: http://developer.android.com/reference/android/hardware/SensorEvent.html#timestamp

So assuming you are correctly setting the event timestamp, in order to ignore events that are triggered less than 5 seconds since the last event, you would need to use a value of 5000000000 .

@Override
public void onSensorChanged(SensorEvent event) {
    if(event.sensor.getType() == Sensor.TYPE_LINEAR_ACCELERATION) {

            long actualTime = event.timestamp; //get the event's timestamp
            int value = (int) event.values[0];
            if(actualTime - lastUpdate > 5000000000) {
                Log.d(TAG, "" + value);
                lastUpdate = actualTime;
            }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM