I have an Android application in which on one activity I am using Google Maps API V2 and I have a second activity which has an Accelerometer on it. I am switching between these two activities by using respective buttons. I am trying to use the Accelerometer to detect braking when the user is driving and place a marker on the Map when that happens.
If I start the Accelerometer activity and then switch to my Map activity I can see using Log.d that the Accelerometer keeps getting its values continuously from onSensorChanged so the activity is not being shut down which is good for me. For some reason though I can't seem to be able to grab the values on the Map activity as they're coming up as 0.0 0.0 0.0 or null null null depending on what I use. Can someone please tell me how I can do this?
UPDATE
Main part of Accelerometer code:
@Override
public void onSensorChanged(SensorEvent e) {
// TODO Auto-generated method stub
// alpha is calculated as t / (t + dT)
// with t, the low-pass filter's time-constant
// and dT, the event delivery rate
if (e.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
// - + +
gravity[0] = alpha * gravity[0] + (1 - alpha) * e.values[0];
gravity[1] = alpha * gravity[1] + (1 - alpha) * e.values[1];
gravity[2] = alpha * gravity[2] + (1 - alpha) * e.values[2];
acceleration[0] = e.values[0] - gravity[0];
acceleration[1] = e.values[1] - gravity[1];
acceleration[2] = e.values[2] - gravity[2];{
txtX.setText(""+Math.round((acceleration[0] * 100.0) / 100.0));
txtY.setText(""+Math.round((acceleration[1] * 100.0) / 100.0));
txtZ.setText(""+Math.round((acceleration[2] * 100.0) / 100.0));
}
I would like to get the Accelerometer values in the onLocationChanged listener of the Map activity so that I may place a marker as soon as deceleration is detected.
If you can see log messages telling you that you are still receiving data from sensor, you are probably still registered with the activity in the background. This is not a good idea, since you can drain your battery quickly (stop receiving data from sensor when you don't need it anymore).
To unregister, add this:
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(this);
}
Back to your question, you need to register also with the Map activity in order to receive data from sensor. Another solution may be to receive data in Service.
You can find more information about sensors here: http://developer.android.com/guide/topics/sensors/sensors_overview.html