在應用程序中使用SensorManager.getOrientation()
來得到原始數據。android
public static float[] getOrientation (float[] R, float[] values)
R
用來保存磁場和加速度的數據,經過該函數獲取方位角。pitch
傾斜角即由靜止狀態開始,先後翻轉,手機頂部往上擡起(0~-90),手機尾部往上擡起(0~90)roll
旋轉角 即由靜止狀態開始,左右翻轉,手機左側擡起(0~90),手機右側擡起(0~-90)經過函數getRotationMatrix
獲取R
數組
public static boolean getRotationMatrix (float[] R, float[] I, float[] gravity, float[] geomagnetic)
sensorManager.registerListener(this, acc_sensor, SensorManager.SENSOR_DELAY_GAME); sensorManager.registerListener(this, mag_sensor,SensorManager.SENSOR_DELAY_GAME);
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.view.Menu; import android.widget.TextView; 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]; TextView showTV = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); show_change=(TextView) findViewById(R.id.show_change); 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_GAME); sensorManager.registerListener(this, mag_sensor,SensorManager.SENSOR_DELAY_GAME); } @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; } // 回調方法 @Override public void onSensorChanged(SensorEvent event) { if(event.sensor.getType() == Sensor.TYPE_ACCELEROMETER){ accValues = event.values.clone(); } else if(event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD){ magValues = event.values.clone(); } /** * r:要填充的旋轉數組 * I: 將磁場數據轉換進實際的重力座標中,通常默認狀況下能夠設置爲null * gravity: 加速度傳感器數據 * geomagnetic:地磁傳感器數據 */ SensorManager.getRotationMatrix(r, null, accValues, magValues); /** * R:旋轉數組 * values:模擬方向傳感器的數據 */ SensorManager.getOrientation(r, values); //將弧度轉化爲角度後輸出 StringBuffer buff = new StringBuffer(); for(float value : values){ value=(float) Math.toDegrees(value); buff.append(value + " "); } showTV.setText(buff.toString()); } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { } }