如何在Android中使用陀螺仪

时间:2015-10-05 20:46:06

标签: android gyroscope

我需要在我的应用程序中计算yz角度。我试图使用陀螺仪,但它不起作用。我的手机甚至没有输入功能onSensorChanged。你能帮助我吗?这是我的代码

MainActivity:

public class mainActivity extends Activity implements SensorEventListener {

private SensorManager mSensorManager;
private Sensor mSensor;

private float xy_angle;
private float xz_angle;
private float yz_angle;

private TextView yzPlane;


public  void onAccuracyChanged(Sensor sensor, int accuracy)
{

}
protected void onResume()
{
    super.onResume();
}
protected void onPause()
{
    super.onPause();
}
public void onSensorChanged(SensorEvent sensorEvent)
{
    xy_angle = sensorEvent.values[0];
    xz_angle = sensorEvent.values[1];
    yz_angle = sensorEvent.values[2];

    Log.i("Test", "Trying to change sensor" + String.valueOf(xy_angle));
    yzPlane.setText("Angle is: " + String.valueOf(yz_angle));
}
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
    mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
    mSensorManager.registerListener(this, mSensor, SensorManager.SENSOR_DELAY_FASTEST);
    yzPlane = (TextView) findViewById(R.id.yzPlane);


}

我在清单文件中也有使用功能:

<uses-feature android:name="android.hardware.sensor.gyroscope" android:required="true"/>

我有索尼Xperia M2所以它有一个陀螺仪。但亚行正在给我这个错误:

  

21681-21681 / com.example.orientationsensor E / SensorManager:传感器或监听器为空

1 个答案:

答案 0 :(得分:1)

A̶s̶̶i̶̶k̶n̶o̶w̶,̶̶X̶p̶e̶r̶i̶a̶̶M̶2̶̶d̶o̶e̶s̶n̶'̶t̶̶h̶a̶v̶e̶̶a̶̶g̶y̶r̶o̶s̶c̶o̶p̶e̶.̶尝试注册另一个传感器,f.e。加速度计,看看是否调用了onSensorChanged。也许是错误...