What happens when onSensorChanged() in called befo

2019-06-07 17:27发布

问题:

This is my function.

 public void onSensorChanged(SensorEvent event)
    {

            if (event.sensor.getType() == Sensor.TYPE_LINEAR_ACCELERATION)
            {
               //DO A JOB...
            }
     }      

My question is what happens if onSensorChanged() is called while it is finishing the current job?

回答1:

If onSensorChanged gets called again while the previous sample is being worked on then onSensorChanged will be working on two samples at once which may be a problem for whatever is happening with the end result of the calculation. I believe that it is just one thread delivering the sensor event however so really it shouldn't get called again until the processing is done with this one.

In general practive though all processing should be done in another thread and onSensorChanged should return as quickly as possible so other receivers can act on the data as well. Also copy the data, don't pass the reference to the sensor data since the SensorData object may be re-used and if you keep a reference around the data may change by the time you go to use it.