我有 Android 代码,我试图在按下按钮时从手机获取加速度计数据。这是我的代码:
public class MainActivity extends Activity implements SensorEventListener{
private SensorManager aSensorManager;
private TextView ax;
private TextView ay;
private TextView az;
private float xa ;
private float ya ;
private float za ;
public Vector<Float> vecA_x;
private Vibrator v;
long[] pattern = { 0, 200, 500 };
long cap = 0;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// dataBase = DataBaseManager;
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
ax = (TextView) findViewById(R.id.textView4);
ay = (TextView) findViewById(R.id.textView5);
az = (TextView) findViewById(R.id.textView6);
aSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
findViewById(R.id.button1).setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN){
start();
return true;
}
if(event.getAction() == MotionEvent.ACTION_UP){
//vibe(pattern);
onPause();
return true;
}
return false;
}
});
}
public void onSensorChanged(SensorEvent event){
if(event.sensor.getType() == Sensor.TYPE_ACCELEROMETER){
float x=event.values[0];
vecA_x.addElement(x); // here the error
runAcce(event);
}
}
}
private void vibe(long[] p){
v.vibrate(p, -1);
}
private void runAcce(SensorEvent event){
float[] values = event.values;
xa = values[0]; gx.setText((xa) + "");
ya = values[1]; gy.setText((ya) + "");
za = values[2]; gz.setText((za) + "");
}
public void onAccuracyChanged(Sensor sensor, int accuracy){
}
private void start(){
aSensorManager.registerListener(this, aSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),SensorManager.SENSOR_DELAY_NORMAL);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
@Override
protected void onResume(){
super.onResume();
}
@Override
protected void onPause(){
super.onPause();
aSensorManager.unregisterListener(this);
}
}
当它在我的设备上运行时,当我按下按钮时它会强制关闭。我在这里是错误代码:
float x=event.values[0];
vecA_x.addElement(x); // here the error
我不知道该怎么办,我的意思是vector是动态数组并且能够捕获值。我的问题是:如何在我的代码中获取传感器数据以进行矢量化?我应该写什么?请帮我。