我是 Android 编程的新手,只是在玩耍以了解更多信息。我正在尝试使用陀螺仪,但是我注意到当我将陀螺仪平放在桌子上时,值仍在移动。如果我没有错,那是由于一些漂移问题。这些是我的以下代码。
public class MainActivity extends Activity implements SensorEventListener {
private SensorManager sm = null;
private Sensor mGyroscope=null;
TextView txt;
@Override
protected void onCreate(Bundle savedInstanceState) {
sm = (SensorManager) getSystemService(SENSOR_SERVICE);
mGyroscope = sm.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txt = (TextView) findViewById(R.id.txt);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
protected void onResume() {
super.onResume();
sm.registerListener(this, mGyroscope, SensorManager.SENSOR_DELAY_NORMAL);
}
protected void onPause() {
super.onPause();
sm.unregisterListener(this);
}
@Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
txt.setText("Orientation X (Roll) :"+ Float.toString(event.values[2]) +"\n"+
"Orientation Y (Pitch) :"+ Float.toString(event.values[1]) +"\n"+
"Orientation Z (Yaw) :"+ Float.toString(event.values[0]));
}
}
我阅读了 android api,但我并没有真正理解它的含义。希望有人可以在这里帮助我。
附上参考:http: //developer.android.com/reference/android/hardware/SensorEvent.html#values