TYPE_ROTATION_VECTOR无法在某些设备上运行

时间:2013-06-07 07:18:25

标签: java android

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

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);
  }

}

2 个答案:

答案 0 :(得分:1)

您必须检查mRotVectSensor是否为空值。对于Sensor.TYPE_ROTATION_VECTOR,设备必须有gyroscope

答案 1 :(得分:0)

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