1

我正在設計一個需要檢查設備方向(方位角,俯仰角和滾轉角)的應用程序。我用下面的代碼來實現這一目標:Android SensorManager.getOrientation()返回介於-PI/2和PI/2之間的間距

@Override 
public void onSensorChanged(SensorEvent event) { 
    if(event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) 
     gravityMatrix = event.values.clone();// Fill gravityMatrix with accelerometer values 
    else if(event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) 
     geomagneticMatrix = event.values.clone();// Fill geomagneticMatrix with magnetic-field sensor values 
    if(gravityMatrix != null && geomagneticMatrix != null){ 
     RMatrix = new float[16]; 
     IMatrix = new float[16]; 

     SensorManager.getRotationMatrix(RMatrix, IMatrix, gravityMatrix, geomagneticMatrix);// Retrieve RMatrix, necessary for the getOrientation method 
     SensorManager.getOrientation(RMatrix, orientation);// Get the current orientation of the device 
    } 
} 

現在我能夠從「方向」浮動[]得到方位,俯仰和滾動值。對於方位角和滾轉值(它返回正確的角度)一切都很好,但是當我打印音高值(方向[1])時,我總是檢索到PI/2和-PI/2之間的角度。我不明白爲什麼?我無法檢索到大於PI/2或小於-PI/2的角度。只要我有一個+ - PI/2的角度,並繼續旋轉我的設備(Samsung Galaxy S2),角度在達到PI/2值後突然下降。

任何人都可以解釋爲什麼傾斜角度表現得如此不尋常嗎?

在此先感謝!

回答

5

節距的計算公式爲pitch = (float) Math.asin(-RMatrix[7]);arcsin功能的範圍是[-PI/2, PI/2],所以asin只能取值在-PI/2PI/2之間。

+0

奧克,非常感謝。這真的很有道理,我不知道。然而,我必須知道這兩個方向有相同音高的差異,所以我想我會使用方位角值。當設備在X軸上旋轉時,它會從負變爲正。如果這有效,我會告訴你。 – user1176420

+0

我找到了解決方案!其實很簡單: 'if(gravityMatrix [2] <0) \t \t \t \t orientation [1] =(float)(Math.PI - orientation [1]);'' 它的工作原理是當設備在其X軸上旋轉時,z軸上的重力從正變爲負。 因此,這將返回正確的音調(0和PI之間的值,0和-PI) 感謝您的解釋! – user1176420

+0

在我的索尼Xperia Z5P上,對於球場來說,我看到一系列值從-0(平坦表)到-90(站起來)並回到-0(桌上正反面),所以我沒辦法知道什麼是上下!有了這個修復程序,我終於可以讓應用程序決定用戶是仰視還是仰視。希望這不是硬件特定的! –