Reputation: 786
I have the following class to read data from accelerometer
:
public class Accelerometer implements SensorEventListener {
private SensorManager mSensorManager;
private Sensor mAccelerometer;
float deltaX;
float deltaY;
float deltaZ;
Activity activity;
public Accelerometer(Activity act)
{
this.activity = act;
mSensorManager = (SensorManager) this.activity.getSystemService(Context.SENSOR_SERVICE);
mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
}
public float getDeltaX()
{
return this.deltaX;
}
public float getDeltaY()
{
return this.deltaY;
}
public float getDeltaZ()
{
return this.deltaZ;
}
@Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
deltaX = event.values[0];
deltaY = event.values[1];
deltaZ = event.values[2];
}
}
and I am accessing this class from my main activity
class using the following code:
Accelerometer sbt = new Accelerometer (this);
tvX.setText(Float.toString(sbt.getDeltaX()) + " " +Float.toString(sbt.getDeltaY()) + " "+Float.toString(sbt.getDeltaZ()));
However, it always shows me 0, 0, 0. not sure whats wrong with current code. any help would be highly appreciated.
Upvotes: 1
Views: 279
Reputation: 93708
THe accelerometer (and all sensor data) works on a callback system. It won't call you until the next time it reads the sensor, and it will continue to call your onSensorChanged until you unregister. But if you try to set the text immediately after registering, you won't have been called yet. You need to set the textView in onSensorChanged, when you're updated with new values.
Upvotes: 2