android SensorEventListener problem

不打扰是莪最后的温柔 提交于 2019-12-19 04:47:32

问题


I am trying to create an application which reads data from digital compass. I tried to reuse the code from the book Professional Android Application Development but the IDE displayed a note

The type SensorListener is deprecated

I guess it is because the code from the book is written for the earlier SDK version so I tried to use SensorEventListener instead.

Then when I tried to register the listener

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

an error appeared:

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

so I tried to cast SensorEventListener to SensorListener, but the application doesn't work.

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

Thank you.


回答1:


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




回答2:


You actually need to pass in a Senor object, not just the ID of it.

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




回答3:


The method is just deprecated, you have to use

registerListener(SensorEventListener, Sensor, int) 

instead.




回答4:


I had the same problem but when I casted the first 2 parameters as (SensorEventListener) and (Sensor) it worked. I then realised the problem was that for some reason I had declared the Sensor as type "Object" and not "Sensor", so Eclipse failed to identify the types of parameters.

This worked for me:

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

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



来源:https://stackoverflow.com/questions/1935854/android-sensoreventlistener-problem

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!