我需要能够在我的场景类中实现 SensorEventListener,但要进行设置,似乎传感器必须为这样的代码使用 Activity 类:
SensorManager sensorManager = (SensorManager) this.getSystemService(Context.SENSOR_SERVICE);
sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_GAME);
即使我是在 Activity 课上做的,我也需要在场景课上使用加速度计。有办法做到这一点吗?
最佳答案
您可以通过创建使您的类实现 SensorEventListener
来实现此目的,例如:
public class MySensor implements SensorEventListener {
Context context;
public InputAccelerometerEx(Context context) {
this.context = context;
SensorManager manager =
(SensorManager)context.getSystemService( Context.SENSOR_SERVICE );
Sensor accel = manager.getDefaultSensor( Sensor.TYPE_ACCELEROMETER );
manager.registerListener( this, accel, SensorManager.SENSOR_DELAY_GAME );
}
public void onSensorChanged(SensorEvent event) {
// respond to sensor changes here :)
}
// implement remaining sensor methods here..
}
现在只需在 Activity 的 onCreate()
中创建该类的实例,例如:
public class MyActivity extends Activity {
MySensor sensor;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate( savedInstanceState );
sensor = new MySensor( this );
}
}
当然,这些只是示例,您可以简单地将 SensorEventListener
的实现添加到您的场景类中,并在您的 Activity 中创建它的实例,而不是使用单独的类。
关于android - 在非 Activity 类中使用传感器,Android/Andengine,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21355889/