Search code examples
androidandroid-custom-viewandroid-sensors

Can you use the SensorEventListener in a custom view in Android?


I am trying to create a custom view where a bitmap moves around with the movement of your phone.

So I created the custom view and implemented sensorEventListener:

public class MovingStarView extends View implements SensorEventListener {
    private SensorManager sm;
    private Sensor mAccelerometer;

.....Other Initialization stuff.....

private void initSensor(){
    // Get an instance of the SensorManager
    sm = (SensorManager) getSystemService(SENSOR_SERVICE); <---NOT RESOLVED
    //Get the Accelerometor
    mAccelerometer = sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
}

Eclipse is saying that SENSOR_SERVICE cannot be resolved. Should I be calling this differently?

Is it possible to do this or will I have to do the Sensor listening on the Activity that calls the custom view?


Solution

  • You need context object in your view. Then Call
    sm = (SensorManager) context.getSystemService(context.SENSOR_SERVICE)