Can you use the SensorEventListener in a custom view in Android?
-
15-04-2021 - |
문제
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?
해결책
You need context
object in your view.
Then Call
sm = (SensorManager) context.getSystemService(context.SENSOR_SERVICE)
다른 팁
Try importing android.content.Context
Also try Context.SENSOR_SERVICE to access it through the Context namespace.
And yes, you should be able to make your View use SensorEventListener. Your View object can implement any number of interfaces you'd like :) (though from an object design standpoint, you may want to avoid this).