gpt4 book ai didi

java - onSensorChanged() 中的值不会存储在变量中

转载 作者:行者123 更新时间:2023-12-01 22:08:49 25 4
gpt4 key购买 nike

我有以下函数来监听加速度计和磁力计值:

  // Storage for Sensor readings
public float[] mGravity = new float[3];
public float[] mGeomagnetic = new float[3];

public void registerSensors(Context context) {
// First, get an instance of the SensorManager
SensorManager sMan = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);

// Second, get the sensor you're interested in
Sensor magnetField = sMan.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);

// Get a reference to the accelerometer
Sensor accelerometer = sMan.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);

// Third, implement a SensorEventListener class
SensorEventListener magnetListener = new SensorEventListener() {
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// do things if you're interested in accuracy changes
}

public void onSensorChanged(SensorEvent event) {
mGravity = new float[3];
//Log.i("LocationUpdater", "magnetometer updated");
System.arraycopy(event.values, 0, mGravity, 0, 3);
//Log.i("LocationUpdater", Float.toString(mGravity[0]));

}
};

SensorEventListener accelListener = new SensorEventListener() {
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// do things if you're interested in accuracy changes
}

public void onSensorChanged(SensorEvent event) {
mGeomagnetic = new float[3];
//Log.i("LocationUpdater", "accelerometer updated");
System.arraycopy(event.values, 0, mGeomagnetic, 0, 3);
}
};


//mGravity[0] = 5;

// Finally, register your listener
sMan.registerListener(magnetListener, magnetField, SensorManager.SENSOR_DELAY_NORMAL);
sMan.registerListener(accelListener, accelerometer, SensorManager.SENSOR_DELAY_NORMAL);

Log.i("LocationUpdater","Listeners registered");

}

之后,我尝试在类中的另一个方法中访问 mGravity:

  public double getUserDirection() {
Log.i("LocationUpdater", Float.toString(mGravity[0]));
if (mGravity != null && mGeomagnetic != null) {

float rotationMatrix[] = new float[9];

...
}

但是,从传感器读取的值不会写入数组,所有值都保持 0。这是为什么?

所有方法都是从另一个类中这样调用的:

 SensorUpdater updater = new SensorUpdater();
updater.startBlukii(context);
updater.registerSensors(context);
double direction = updater.getUserDirection();
Log.i(LOG_TAG, Double.toString(direction));

最佳答案

我通过访问监听器内的如下变量解决了这个问题:LocationUpdater.mGravity,这似乎可以解决它。

 public void onSensorChanged(SensorEvent event) {
System.arraycopy(event.values, 0, LocationUpdater.mGravity, 0, 3);
}

关于java - onSensorChanged() 中的值不会存储在变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58672868/

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