1

我制作了一个程序,使用 TYPE_ROTATION_VECTOR 来获取手机的方向。该程序适用于某些三星 Galaxy 的手机,但不适用于索尼 xperia neo v ..所有手机都有 api >= 9 的 android 版本。可能是什么问题 ?

package com.example.sensortest;

import android.annotation.TargetApi;
import android.app.Activity;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Build;
import android.os.Bundle;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends Activity implements SensorEventListener{
TextView t1,t2,t3;
private SensorManager mSensorManager;
private Sensor mRotVectSensor;
private float[] orientationVals=new float[3];
private float[] mRotationMatrix=new float[16];
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    t1=(TextView)findViewById(R.id.TextView1);
    t2=(TextView)findViewById(R.id.TextView2);
    t3=(TextView)findViewById(R.id.TextView3);
    mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
    mRotVectSensor=mSensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR);
}

@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;
}
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
@Override
public void onSensorChanged(SensorEvent event)
{
    if(event.sensor.getType()==Sensor.TYPE_ROTATION_VECTOR)
    {
        SensorManager.getRotationMatrixFromVector(mRotationMatrix,event.values);
        SensorManager.remapCoordinateSystem(mRotationMatrix,SensorManager.AXIS_X, SensorManager.AXIS_Z, mRotationMatrix);
        SensorManager.getOrientation(mRotationMatrix, orientationVals);
        orientationVals[0]=(float)Math.toDegrees(orientationVals[0]);
        orientationVals[1]=(float)Math.toDegrees(orientationVals[1]);
        orientationVals[2]=(float)Math.toDegrees(orientationVals[2]);
        t1.setText(String.valueOf(orientationVals[0]));
        t2.setText(String.valueOf(orientationVals[1]));
        t3.setText(String.valueOf(orientationVals[2]));
    }
}
@Override
  public void onAccuracyChanged(Sensor sensor, int accuracy) {

  }
@Override
  protected void onResume() {
    super.onResume();
    // register this class as a listener for the orientation and
    // accelerometer sensors
    mSensorManager.registerListener(this,
        mRotVectSensor,
        10000);
  }

  @Override
  protected void onPause() {
    // unregister listener
    super.onPause();
    mSensorManager.unregisterListener(this);
  }

}

4

2 回答 2

1

您必须检查mRotVectSensor空值。因为Sensor.TYPE_ROTATION_VECTOR设备必须有一个gyroscope.

于 2013-06-07T07:21:53.403 回答
0

我可能无法解决您的问题,但请确保您在 SensorManager.remapCoordinateSystem 中使用不同的矩阵(请参阅文档)。那里说:(参数)outR-变换后的旋转矩阵。inR 和 outR 不应该是同一个数组。

于 2015-10-27T16:10:47.853 回答