为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

斯蒂芬大帝 2024-01-25 10:34:15
我有以下函数用于监听加速度计和磁力计值:  // 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);            }        };但是,从传感器读取的值不会写入数组,所有值都会保留0。这是为什么?
查看完整描述

1 回答

?
九州编程

TA贡献1785条经验 获得超4个赞

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

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


查看完整回答
反对 回复 2024-01-25
  • 1 回答
  • 0 关注
  • 23 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信