我查看了许多其他线程,这些线程显示了如何使用加速度计值,甚至跨越多个类,但是我发现的方法都没有工作,无论我做什么,我都无法在其他类中显示这些值比定义它们的那个。我知道我有一个可以工作的加速度计,并且我的 AccelerometerReader 类正在正确获取值,因为我已经通过在该类中打印它们来测试它们。我在下面有一些代码,但我不知道为什么它不起作用,尽管我相信只有起始值被传递到另一个类,并且它们没有更新。任何帮助将非常感激!
AccelerometerReader 类
import android.app.Activity;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
public class AccelerometerReader extends Activity implements SensorEventListener {
private SensorManager sensorManager;
private float ax; // these are the acceleration in x, y and z axes
private float ay;
private float az;
public AccelerometerReader(float x, float y, float z) {
this.ax = x;
this.ay = y;
this.az = z;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.main);
sensorManager=(SensorManager) getSystemService(SENSOR_SERVICE);
sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
@Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() != Sensor.TYPE_ACCELEROMETER)
return;
if (event.sensor.getType()==Sensor.TYPE_ACCELEROMETER){
setValueX(event.values[0]);
setValueY(event.values[1]);
setValueZ(event.values[2]);
}
}
public void setValueX(float x) {
ax=x;
}
public float getValueX() {
return ax;
}
public void setValueY(float y) {
ay=y;
}
public float getValueY() {
return ay;
}
public void setValueZ(float z) {
az=z;
}
public float getValueZ() {
return az;
}
}
加速度计类
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class Accelerometer extends Activity {
private float ax, ay, az;
TextView tvX, tvY, tvZ;
AccelerometerReader acc = new AccelerometerReader(ax, ay, az);
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tvX = (TextView) findViewById(R.id.tvX);
tvY = (TextView) findViewById(R.id.tvY);
tvZ = (TextView) findViewById(R.id.tvZ);
tvX.setText("" + ax);
tvY.setText("" + ay);
tvZ.setText("" + az);
}
}