我想读取方向和磁场。
我用
if (e.Sensor.Type == SensorType.Orientation)
{ ... }
if (e.Sensor.Type == SensorType.MagneticField)
{ ... }
我试过
_sensorManager.RegisterListener(this, _sensorManager.GetDefaultSensor(SensorType.All), SensorDelay.Game);
和
_sensorManager.RegisterListener(this, _sensorManager.GetDefaultSensor(SensorType.MagneticField), SensorDelay.Game);
和
_sensorManager.RegisterListener(this, _sensorManager.GetDefaultSensor(SensorType.Orientation), SensorDelay.Game);
和
_sensorManager.RegisterListener(this, _sensorManager.GetDefaultSensor(SensorType.Orientation | SensorType.MagneticField), SensorDelay.Game);
和
mOrientation = _sensorManager.GetDefaultSensor(SensorType.Orientation);
mMagnetisch = _sensorManager.GetDefaultSensor(SensorType.MagneticField);
if (mOrientation != null)
_sensorManager.RegisterListener(this, mOrientation, SensorDelay.Game);
if (mMagnetisch != null)
_sensorManager.RegisterListener(this, mMagnetisch, SensorDelay.Game);
但每次 方向或磁场显示。怎么解决?
PS:我的代码被剥离到传感器部分:http://pastebin.com/uXVRJmSq
答案 0 :(得分:1)
首先,让您的Activity
实施ISensorEventListener
。它看起来像这样:
public void OnAccuracyChanged(Sensor sensor, SensorStatus accuracy)
{
// Do nothing.
}
public void OnSensorChanged(SensorEvent e)
{
var sensor = e.Sensor;
if (sensor.Type == SensorType.Orientation) {
Toast.MakeText(this, "Orientation: " + e.Values[0], ToastLength.Short).Show();
}else if (sensor.Type == SensorType.MagneticField) {
Toast.MakeText(this, "MagneticField: " + e.Values[0], ToastLength.Short).Show();
}
}
然后,在Activity
的{{1}}方法中,注册这两个听众。
OnCreate()