2017-08-09 43 views
0

我正尝试在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(); 
    } 

} 

完整的代码引擎收录是在这里:https://pastebin.com/uREm9Esd

谢谢你的时间提前

+0

请解释一下当你说“加速计保持返回空值”时你的意思。你的意思是这行代码返回null: 'sensorMan.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);'? – CzarMatt

+0

acclerometer数据数组sensorEvent似乎始终以null结尾 –

回答

0
mAccelLast = mAccelCurrent; 
mAccelCurrent = (float) Math.sqrt(x*x + y*y + z*z); 
float delta = mAccelCurrent - mAccelLast; 

问题是第一线之后,它必须去三角洲计算之前; 有这样的错误,你不是null你有0值!

仅供参考:我有时在加速计中听到它确实可以返回null,但没有看到这种情况;