gpt4 book ai didi

java - 如何在android中使用传感器加速度计检测运动

转载 作者:行者123 更新时间:2023-11-30 01:15:53 27 4
gpt4 key购买 nike

这是我在 Activity 中的代码,但是 mAccel 的值总是 0。我想将 mAccel 的值与灵敏度值进行比较。有人可以帮我解决这个问题吗?

   private float mAccel;
private float mAccelCurrent;
private float mAccelLast;
private float[] mGravity;
float sensitivityLevel = 2.0f;

private SensorManager sensorManager;
private Sensor accel;

sensorManager=(SensorManager)getSystemService(SENSOR_SERVICE);
accel = sensorManager.getDefaultSensor(1);

mAccel = 0.00f;
mAccelCurrent = SensorManager.GRAVITY_EARTH;
mAccelLast = SensorManager.GRAVITY_EARTH;
@Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() ==1){
mGravity = event.values.clone();
// Shake detection
float x = mGravity[0];
float y = mGravity[1];
float z = mGravity[2];
mAccelLast = mAccelCurrent;
mAccelCurrent = FloatMath.sqrt(x*x + y*y + z*z);
float delta = mAccelCurrent - mAccelLast;
mAccel = mAccel * 0.9f + delta;

if(mAccel > sensitivityLevel){
play_alarm("car alarm");
}
}

最佳答案

需要注册监听器

    sm = (SensorManager) getSystemService(SENSOR_SERVICE);
if(sm.getSensorList(Sensor.TYPE_ACCELEROMETER).size()!=0){
Sensor s = sm.getSensorList(Sensor.TYPE_ACCELEROMETER).get(0);
sm.registerListener(this,s, SensorManager.SENSOR_DELAY_NORMAL);
}

您应该使用日志或调试来检查该方法是否被调用。

关于java - 如何在android中使用传感器加速度计检测运动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37867683/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com