Jonas Meeuws Jonas Meeuws - 3 months ago 29
Java Question

Sensor change doesn't trigger onSensorChanged

I just started out on android and java yesterday, and i'm having a problem. I'm trying to output a sensor's values to some TextViews. The text updates, but with the values set at definition. onSensorChanged should update these values right?

import [...]

public class MainActivity extends Activity implements SensorEventListener {

public float[] gravity = {0,0,0};

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

final TextView gravxTxtView = (TextView) findViewById(R.id.gravxTxtView);
final TextView gravyTxtView = (TextView) findViewById(R.id.gravyTxtView);
final TextView gravzTxtview = (TextView) findViewById(R.id.gravzTxtView);

final Handler handler = new Handler();
handler.postDelayed(
new Runnable() {
@Override
public void run() {
gravxTxtView.setText("Gravity x: " + Float.toString((gravity[0])));
gravyTxtView.setText("Gravity y: " + Float.toString((gravity[1])));
gravzTxtview.setText("Gravity z: " + Float.toString((gravity[2])));
}
}, 500);
}

@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}

@Override
public void onSensorChanged(SensorEvent event) {
if(event.sensor.getType() == Sensor.TYPE_ACCELEROMETER){
gravity[0] = event.values[0];
gravity[1] = event.values[1];
gravity[2] = event.values[2];
}
}
}

Answer

There are some serious steps you are missing 1. Get the instance of sensor manager

SensorManager sensorManager=(SensorManager)getSystemService(SENSOR_SERVICE);

2. Get the instance of the sensor

Sensor accel=sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);

3. Register sensor to the lister class which implements SensorEventListener in your case you have implemented on the MainActivity so it will be this

sensorManager.registerListener(this, accel, SensorManager.SENSOR_DELAY_NORMAL);

now when certain change will happen it will call the onSensorChanged method ,please let me know its working or not