我尝试在Android中使用加速器,但在获取任何结果时遇到问题。
加速度计一直返回null,我不太确定事件监听器是否是问题,或其他什么。
我认为与此问题相关:
public class CalibrateScreen extends AppCompatActivity implements SensorEventListener{
private SensorManager sensorMan;
private float mAccel;
private float mAccelCurrent;
private float mAccelLast;
boolean Calibration;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calibrate_screen);
sensorMan = (SensorManager)getSystemService(SENSOR_SERVICE);
Sensor accelerometer = sensorMan.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sensorMan.registerListener(CalibrateScreen.this, accelerometer, SensorManager.SENSOR_DELAY_NORMAL);
mAccel = 0.00f;
mAccelCurrent = SensorManager.GRAVITY_EARTH;
mAccelLast = SensorManager.GRAVITY_EARTH;
Calibration = true;
@Override
public void onSensorChanged(SensorEvent sensorEvent) {
if (sensorEvent.sensor.getType() == Sensor.TYPE_ACCELEROMETER){
// Shake detection
float x = sensorEvent.values[0];
float y = sensorEvent.values[1];
float z = sensorEvent.values[2];
mAccelLast = mAccelCurrent;
mAccelCurrent = (float) Math.sqrt(x*x + y*y + z*z);
float delta = mAccelCurrent - mAccelLast;
mAccel = mAccel * 0.9f + delta;
//mAccel is the current acceleration.
if (Calibration) {
addMember(mAccel);
}
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int i) {
}
@Override
protected void onResume() {
super.onResume();
sensorMan.registerListener(this, sensorMan.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
}
@Override
protected void onStart() {
super.onStart();
sensorMan.registerListener(this, sensorMan.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
}
@Override
protected void onStop() {
sensorMan.unregisterListener(this);
super.onStop();
}
}
完整代码pastebin在这里:https://pastebin.com/uREm9Esd
感谢您提前的时间
答案 0 :(得分:0)
mAccelLast = mAccelCurrent;
mAccelCurrent = (float) Math.sqrt(x*x + y*y + z*z);
float delta = mAccelCurrent - mAccelLast;
问题出在第一行,它必须先进行delta计算; 有这样的错误,你没有null,你得到0值!
仅供参考:我听说加速度计有时它确实可以返回零点,但是没有看到这样的情况;