Jonas Meeuws Jonas Meeuws - 4 months ago 43
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};

protected void onCreate(Bundle savedInstanceState) {

final TextView gravxTxtView = (TextView) findViewById(;
final TextView gravyTxtView = (TextView) findViewById(;
final TextView gravzTxtview = (TextView) findViewById(;

final Handler handler = new Handler();
new Runnable() {
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);

public void onAccuracyChanged(Sensor sensor, int accuracy) {

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];


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