我正在开发一个Android应用程序来获取Android设备的方向。
我正在使用以下代码:
public class AccelerometerDirection extends Activity implements SensorEventListener {
TextView textView;
StringBuilder builder = new StringBuilder();
float [] history = new float[2];
String [] direction = {"NONE","NONE"};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
textView = new TextView(this);
setContentView(textView);
SensorManager manager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
Sensor accelerometer = manager.getSensorList(Sensor.TYPE_ACCELEROMETER).get(0);
manager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_GAME);
}
@Override
public void onSensorChanged(SensorEvent event) {
float xChange = history[0] - event.values[0];
float yChange = history[1] - event.values[1];
history[0] = event.values[0];
history[1] = event.values[1];
if (xChange > 2){
direction[0] = "LEFT";
}
else if (xChange < -2){
direction[0] = "RIGHT";
}
if (yChange > 2){
direction[1] = "DOWN";
}
else if (yChange < -2){
direction[1] = "UP";
}
builder.setLength(0);
builder.append("x: ");
builder.append(direction[0]);
builder.append(" y: ");
builder.append(direction[1]);
textView.setText(builder.toString());
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// nothing to do here
}
}
参考此How can I get the direction of movement using an accelerometer?。
但是工作太可怕了,我没有得到准确的价值。我尝试了不同的常数值,没有用。任何想法请分享。
答案 0 :(得分:1)
此行为您提供50 HZ或100 Hz的非常高频率的值,用于不同的设备
manager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_GAME);
因此,对于每次读数,即使设备处于静止状态,您的输出也会发生变化,因为读取加速度计不是很准确。
因此,要么使用低通滤波器过滤读数,要么使用频率较低的读数(比如1 HZ)
manager.registerListener(this, accelerometer, 1000000);
但低通滤波器是获得平稳行为的最佳选择