【问题标题】:How to save only starting value in onSensorChanged() method?如何在 onSensorChanged() 方法中仅保存起始值?
【发布时间】:2013-07-12 22:00:44
【问题描述】:

我在 onSensorChanged() 方法中使用 getRotationMatrix() 来计算 v[0]、v[1]、v[2] 和相应的方位角、俯仰角和滚动值。我想知道当布尔检测方位角变为真时,如何仅将第一个 v[0] (或相应的方位角)值保存到 firstAzimuth 中?

private boolean detectAzimuth = false;
private float firstAzimuth;

@Override
public void onSensorChanged(SensorEvent event) {

if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
    accValues = event.values.clone();
}

if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
    geoValues = event.values.clone();
}

boolean success = SensorManager.getRotationMatrix(r, i, accValues,
    geoValues);

if (success) {
    SensorManager.getOrientation(r, v);

    if (detectAzimuth) {
    azimuth = v[0] * (180 / Math.PI);
    }
    pitch = v[1] * (180 / Math.PI);
    roll = v[2] * (180 / Math.PI);
}
}

【问题讨论】:

    标签: android rotation sensors


    【解决方案1】:

    您可以检查是否第一次获得方位角的值。如果没有,请获取该值并将 detectAzimuth 设为 true。然后将值保存在 SharedPreference 中。

    现在下一次,检查您是否已经在第一次使用布尔变量detectAzimuth 时获取了方位角的值。如果它是真的,那意味着你已经拿走了它。然后从 Sharedpreference 中获取它并将其分配给firstAzimuth。那你将永远拥有azimuth 的第一个值。

    if (success) {
        SensorManager.getOrientation(r, v);
        if (!detectAzimuth) {  // if not taken yet
            azimuth = v[0] * (180 / Math.PI); // take the value
            detectAzimuth = true; //make the bolean true to know that you've taken the value
            //Store in SharedPreference
            SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
            editor.putFloat("firstAzimuth", azimuth);
            editor.commit();
        }else{ //if already taken value first time
            //get the first value from SharedPreference and assign it to firstAzimuth
            SharedPreferences prefs = getPreferences(MODE_PRIVATE); 
            firstAzimuth = prefs.getFloat("firstAzimuth", 0.0);
            //take the new value
            azimuth = v[0] * (180 / Math.PI); // take the new value but don't store it
        }
        pitch = v[1] * (180 / Math.PI);
        roll = v[2] * (180 / Math.PI);
        }
    }
    

    希望这会有所帮助。仅供参考,这将阻止您获取更多 azimuth 值,因为您已经收到一个值并且每次都在检查它的存在。我不确定你是否想要那个。如果没有,那么我们可以进一步讨论可能性。

    【讨论】:

    • 感谢您的出色回答。如果您能给我一些进一步获取(不保存)方位角值的可能性,同时仍然只保存第一个值,我将不胜感激,因为您不确定,这就是我的目标。
    • 很高兴它有帮助。好的。如果您想获取值但不保存它(第一次除外),请参阅更新的代码。
    • 太棒了!像魅力一样工作。你做主。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-08
    • 1970-01-01
    • 2015-04-21
    • 1970-01-01
    • 2023-04-11
    相关资源
    最近更新 更多