I’m collecting data in my Android app like follows (this is a stripped down version):
public class Main extends Activity {
...
public void log5secs(){
try {
CollectData collectData = new CollectData(this);
// collect data for five seconds in the background
Thread.sleep(5000);
Log.d("unregister", "gyro from Main: "+collectData.gyroscopeResults.size());
fingerprint.finish();
} catch (InterruptedException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
}
public class CollectData implements SensorEventListener {
ArrayList<SensorEvent> gyroscopeResults = new ArrayList<SensorEvent>();
public CollectData(Context context){
sensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
gyroscope = sensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
sensorManager.registerListener(this, gyroscope, SensorManager.SENSOR_DELAY_NORMAL);
}
public void onSensorChanged(SensorEvent event) {
gyroscopeResults.add(event);
Log.d("SensorChanged", "gyro results size: "+gyroscopeResults.size());
}
public void finish(){
unregister();
}
private void unregister() {
Log.d("Unregister", "gyro results size before unregister: "+gyroscopeResults.size());
sensorManager.unregisterListener(this);
}
}
So, the log messages show that every time the onSensorChanged event is called, the size of the ArrayList increases (gets to 26 in five seconds).
However, when the size is requested from Main or due to unregister() being called, the size of the ArrayList is zero. In the debugger, I can’t see where it changes.
What happened to my data???
I’m running it on an HTC Sensation XL.
UPDATE: Got some more info! Out of curiosity, I made the ArrayList gyroscopeResults a static field in the Main class. The effect was interesting – the SECOND time the recording was done, the results of the first were visible (but not the first time). I guess what this means is that the primary thread is finishing before the sensor data is being recorded – some sort of buffering issue???
Your data is not lost, the problem in
Thread.sleep()that halts the program for 5 seconds (including sensor collection) then it executes the linefingerprint.finish();after this it starts the sensor collection.So when you call
Log.d("Unregister", "gyro results size before unregister: "+gyroscopeResults.size());you get0because no sensor data were recorded while the program was sleeping.Here is a few suggestions to make your program working as you expect
To collect the data for 5 seconds, you can use a
Timer(here I am cancelling the timer after 5 seconds, but you can continue collection after clearing theArrayListto not run out of memory)Another solution, might be simpler, if you want to keep
Thread.sleep()is to runlog5secs()within aThreadHowever using
Timerwill be more appropriate if you want continuous sensor logging which you do something with the data every 5 seconds (e.g. log to file and/or clearArrayList)