2

我尝试通过SensorManager.getOrientation. 在此之前我SensorManager.getRotationMatrix用来获取旋转矩阵,但这总是返回false。这是我的活动代码:


public class MainActivity extends Activity implements SurfaceHolder.Callback,  View.OnClickListener{

public final static String DEBUG_TAG = "MainActivity"; private SensorManager sensorManager; private SurfaceView preview; private float[] mGravs; private float[] mGeoMags; private float[] mRotationM; private float[] mOrientation; private Sensor mAccelerometer; private Sensor mMagneticField; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.activity_main); preview = (SurfaceView)findViewById(R.id.SurfaceView1); sensorManager = (SensorManager)getSystemService(SENSOR_SERVICE); mAccelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); mMagneticField = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD); mGravs = new float[3]; mGeoMags = new float[3]; mRotationM = new float[16]; mOrientation = new float[3]; List<Sensor> sensorList = sensorManager.getSensorList(Sensor.TYPE_ALL); for (int nI = 0; nI < sensorList.size(); nI++) { Log.d(DEBUG_TAG, sensorList.get(nI).getName()); } } private SensorEventListener sensorEventListener = new SensorEventListener() { @Override public void onSensorChanged(SensorEvent event) { synchronized (this) { switch (event.sensor.getType()) { case Sensor.TYPE_ACCELEROMETER: System.arraycopy(event.values, 0, mGravs, 0, 3); break; case Sensor.TYPE_MAGNETIC_FIELD: System.arraycopy(event.values, 0, mGeoMags, 0, 3); break; default: return; } if (mGravs != null && mGeoMags != null) { boolean bSuccess = SensorManager.getRotationMatrix(mRotationM, null, mGravs, mGeoMags); if (bSuccess) { SensorManager.getOrientation(mRotationM, mOrientation); } } } } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { // TODO Auto-generated method stub } }; private boolean openHardware() { sensorManager.registerListener(sensorEventListener, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL); sensorManager.registerListener(sensorEventListener, mMagneticField, SensorManager.SENSOR_DELAY_NORMAL); return true; } private void closeHardware() { sensorManager.unregisterListener(sensorEventListener); } @Override protected void onResume() { super.onResume(); openHardware(); } @Override protected void onPause() { super.onPause(); closeHardware(); } @Override protected void onStop() { closeHardware(); super.onStop(); } }

好的,出现这个问题是因为磁场传感器总是返回 [0.0, 0.0, 0.0]。我怎样才能让磁场传感器返回别的东西?

4

1 回答 1

3

我有同样的问题。一切都变得虚假

这个答案帮助了我:https ://stackoverflow.com/a/14224122/1549127

于 2013-07-15T11:40:29.167 回答