I have used:
public class MainGamePanel extends SurfaceView
implements SurfaceHolder.Callback, SensorEventListener
to implement touch events and accelerometer events. Using @Override, I have overriden the touch events, and they are working correctly. I am not getting anything from the accelerometer events though, like onSensorChanged()
Is there an obvious reason why?
You will need to register with the system’s SensorManager in order to receive updates from any sensors. A very basic example on how to do this is given in the documentation of
SensorManager.The steps are:
1) Get a reference to the system’s SensorManager as well as the sensor(s) you would like to listen for updates for. In your case that would at least be the accelerometer. You need to request the SensorManager from a context. Since your
MainGamePanelextends SurfaceView, usegetContext().2) Once you have acquired these, you’ll need to register your class to listen for the actual updates – this is where SensorEventListener comes into the picture. Your SurfaceView implements it, so you should be able to register it as follows:
3) That is actually all you have to do in order to start receiving updates from hardware sensors. From here on, events should start hitting your overridden
onSensorChanged()method. You should however be aware of the fact that it’s common practice to release system resources as soon as you don’t actively use/need them anymore. Hence, don’t forget to unregister for sensor updates. An appropriate place for this would be in anonPause()oronStop()call.Google says:
Hope that helps you. If not, browse a bit around, because there are numerous examples illustrating how to set up a listener for sensor events.