Problem with android SensorEventListener

I am trying to create an application that reads data from a digital compass. I tried to reuse the code from Professional Development for Android, but a note was noted in the IDE

SensorListener type is deprecated

I think this is because the code from the book was written for an earlier version of the SDK, so I tried using SensorEventListener instead.

Then when I tried to register the listener

sensorManager.registerListener(sensorListener, SensorManager.SENSOR_ORIENTATION, SensorManager.SENSOR_DELAY_FASTEST); 

there was an error:

The registerListener (SensorListener, int, int) method in the SensorManager type is not applicable for arguments (SensorEventListener, int, int)

so I tried to apply SensorEventListener to SensorListener, but the application is not working.

Does anyone know how to use the sensor in newer versions of the SDK?

Thanks.

+1
source share
4 answers

There is a separate SensorEventListener class that you need to use. See here .

+8
source

You really need to pass the Senor object, not just its identifier.

Sensor sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION); sensorManager.registerListener(sensorListener, sensor, SensorManager.SENSOR_DELAY_FASTEST)

+6
source

The method is just out of date, you should use

 registerListener(SensorEventListener, Sensor, int) 

instead.

+1
source

I had the same problem, but when I executed the first 2 parameters like (SensorEventListener) and (Sensor), it worked. Then I realized that the problem was that for some reason I declared Sensor as a type of "Object" and not a "Sensor", so Eclipse was not able to identify the parameter types.

This worked for me:

 mSensorManager.registerListener((SensorManager)this, (Sensor)mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL); 

But now I have correctly declared mAccelerometer as a Sensor type; I no longer need casts.

+1
source

All Articles