我具有以下功能来监听加速度计和磁力计的值:
// 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));
答案 0 :(得分:0)
我通过访问侦听器内的变量cairo_region_t
来解决它,这似乎可以解决问题。
LocationUpdater.mGravity