标签:
Android2.2以后 orientation sensors 就被deprecated了
官方建议用acceleration and magnetic sensor 来算
关于这个问题,CSDN上一篇博文讲的非常好
http://blog.csdn.net/flowingflying/article/details/43233315
stack overflow上:
http://stackoverflow.com/questions/10291322/what-is-the-alternative-to-android-orientation-sensor
用法的话直接看代码
package com.turtle920.androidaudioprocess; import android.app.Activity; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.widget.TextView; //实现传感器事件监听:SensorEventListener public class MainActivity extends Activity implements SensorEventListener{ private SensorManager sensorManager; private Sensor acc_sensor; private Sensor mag_sensor; //加速度传感器数据 float accValues[]=new float[3]; //地磁传感器数据 float magValues[]=new float[3]; //旋转矩阵,用来保存磁场和加速度的数据 float r[]=new float[9]; //模拟方向传感器的数据(原始数据为弧度) float values[]=new float[3]; int counter=0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE); acc_sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); mag_sensor = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD); //给传感器注册监听: sensorManager.registerListener(this, acc_sensor, SensorManager.SENSOR_DELAY_NORMAL); sensorManager.registerListener(this, mag_sensor, SensorManager.SENSOR_DELAY_NORMAL); } //传感器状态改变时的回调方法 @Override public void onSensorChanged(SensorEvent event) { if(event.sensor.getType()==Sensor.TYPE_ACCELEROMETER){ accValues=event.values; } else if(event.sensor.getType()==Sensor.TYPE_MAGNETIC_FIELD){ magValues=event.values; } /**public static boolean getRotationMatrix (float[] R, float[] I, float[] gravity, float[] geomagnetic) * 填充旋转数组r * r:要填充的旋转数组 * I:将磁场数据转换进实际的重力坐标中 一般默认情况下可以设置为null * gravity:加速度传感器数据 * geomagnetic:地磁传感器数据 */ SensorManager.getRotationMatrix(r, null, accValues, magValues); /** * public static float[] getOrientation (float[] R, float[] values) * R:旋转数组 * values :模拟方向传感器的数据 */ SensorManager.getOrientation(r, values); if (counter++ % 10==1){ Log.e("DEBUG", "x:"+Math.toDegrees(values[0])+" y:"+Math.toDegrees(values[1])+" z:"+Math.toDegrees(values[2])); } } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { } }
输出的x,y,z三个值是手机沿这个轴的旋转角度
这个地方有个要注意的问题是Macbook的屏幕开合的磁铁磁力会影响磁力传感器。。。调试的时候要注意
标签:
原文地址:http://www.cnblogs.com/turtle920/p/4949254.html