获得多个传感器读数

时间:2013-12-14 00:26:00

标签: android xamarin.android xamarin android-sensors

我想读取方向和磁场。

我用

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

1 个答案:

答案 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()