我正在使用以下类从android手机读取加速度计数据:

public class AccelerometerData extends Activity implements SensorEventListener {

    //variables

    public AccelerometerData()
    {

        mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {
    }

    @Override
    protected void onPause() {
        super.onPause();
        mSensorManager.unregisterListener(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        // TODO: my codes

        }
    }
}


现在从我的主要活动课,我正在调用该课以读取数据

AccelerometerData sbt = new AccelerometerData ();


并显示以下消息,不幸的是AccelerometerData已停止。我是android开发的新手,不确定在这里出了什么问题。

任何帮助将不胜感激。

最佳答案

您正在寻找的答案可能看起来像这样。 MainActivity拥有AccelerometerData类。

public class MainActivity extends Activity {
  priavte AccelerometerData ad;
  private TextView someTextView;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    // "this" allows 'ad' to make calls back to the MainActivity
    ad = new AccelerometerData((SensorManager)getSystemService(SENSOR_SERVICE), this);
    someTextView = (TextView)findViewById(R.id.my_text_view);
  }

  protected void onResume() {
    super.onResume();
    sensorHandler.onResume();
  }

  protected void onPause() {
    super.onPause();
    sensorHandler.onPause();
  }

  protected void setTextViewValue(float[] values){
    someTextView.setText( Float.toString(values[0]) );
  }


然后在AccelerometerData类中,它可能看起来像这样。

public class AccelerometerData implements SensorEventListener {

  private final SensorManager mSensorManager;
  private final Sensor mAccelerometer;
  private final MainActivity ma;

public AccelerometerData(SensorManager sm, MainActivity ma){
    mSensorManager = sm;
    mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
    this.ma = ma
}

protected void onResume() {
    mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
}

protected void onPause() {
    mSensorManager.unregisterListener(this);
}

public void onAccuracyChanged(Sensor sensor, int accuracy) {
}

public void onSensorChanged(SensorEvent event) {
  // Here we call a method in MainActivity and pass it the values from the SensorChanged event
  ma.setTextViewValue( event.values );
}


}

08-16 17:04