2017-08-09 56 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,但沒有看到這種情況;