Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 指南針原理:用 Sensor 感應器取得用戶移動方向

編輯:關於 Android 程式設計

本文以實例講解 Android 如何透過 Sensor 感應器取得用戶的移動方向。以下內容供大家參考。

今天繼續分享第二個重要的感應器應用。取得方向本應是件簡單的事——前面文章裡我們看過 TYPE_ORIENTATION 這個關鍵字,看似可以直接取得設備的移動方向,但新版 SDK 卻加了一句:「TYPE_ORIENTATION This constant is deprecated. use SensorManager.getOrientation() instead.」也就是說,這種方式已被捨棄,官方要求開發者改用 SensorManager.getOrientation() 來取得原本的那些數據。

實際上,Android 取得方向是靠磁場感應器與加速度感應器共同完成的,具體算法 SDK 已經幫我們封裝好了。也就是說,現在取得用戶方向有兩種方式:一是官方推薦的,透過 SensorManager.getOrientation() 取得,這個方法表面看似簡單(那是因為你還沒看到它的參數),實際上需要兩個感應器協同運作,特點是更精準;第二種方法則非常簡單,就像前一篇取得加速度一樣,直接讀取三個軸上的數據。

先從難一點的方法講起,畢竟第一種方式會是 Android 未來的標準選擇,第二種不知何時就會成為歷史。

Android 提供的方向數據是一個 float 陣列,包含三個方向的值,如下圖:

當手機水平放置時,被視為靜止狀態,此時 X、Y 角度均為 0。

values[0] 表示 Z 軸角度,也就是方位角,我們平時判斷東南西北看的就是這個值。經過實驗發現一個有趣的現象:用第一種方式(磁場+加速度)取得的方向,數值範圍是 -180~180,也就是 0 代表正北、90 代表正東、180/-180 代表正南、-90 代表正西;而第二種方式(直接透過方向感應器)的數值範圍則是 0~360,其中 360/0 代表正北、90 代表正東、180 代表正南、270 代表正西。

values[1] 表示 X 軸角度,即俯仰角,由靜止狀態開始前後翻轉;values[2] 表示 Y 軸角度,即翻轉角,由靜止狀態開始左右翻轉。

由此可見,統一取得方向的方法是必要的,因為處理這些數據的算法可能是針對第一種方式設計的,若套用到第二種方式,移植性就會變差。

來看官方方法:

public static float[] getOrientation (float[] R, float[] values)
Since: API Level 3
Computes the device's orientation based on the rotation matrix.
When it returns, the array values is filled with the result:
values[0]: azimuth, rotation around the Z axis.
values[1]: pitch, rotation around the X axis.
values[2]: roll, rotation around the Y axis.
The reference coordinate-system used is different from the world coordinate-system defined for the rotation matrix:
X is defined as the vector product Y.Z (It is tangential to the ground at the device's current location and roughly points West).
Y is tangential to the ground at the device's current location and points towards the magnetic North Pole.
Z points towards the center of the Earth and is perpendicular to the ground.
All three angles above are in radians and positive in the counter-clockwise direction.

通常我們並不需要取得這個函數的返回值,它會依據參數 R[] 的數據來填充 values[],而後者正是我們想要的。

那麼 R 是什麼?又該如何取得?

R[] 是一個旋轉矩陣,用來保存磁場與加速度的數據,你可以把它理解為「未加工的方向數據」。R 透過下面的靜態方法取得,這個方法同樣是用來填充 R[]:

public static boolean getRotationMatrix (float[] R, float[] I, float[] gravity, float[] geomagnetic)

參數說明:

第一個是待填充的 R 陣列,大小為 9;
第二個是一個轉換矩陣,用來把磁場數據轉換進實際的重力座標系,一般預設可設為 null;
第三個是大小為 3 的陣列,存放從加速度感應器取得的數據(在 onSensorChanged 中);
第四個是大小為 3 的陣列,存放從磁場感應器取得的數據(同樣在 onSensorChanged 中)。

基本邏輯就是這樣。下面演示一個簡單的方向測試範例,可以隨時監聽用戶朝向:

 /* * @author octobershiner * 2011 07 28 * SE.HIT * 一個演示通過磁場和加速度兩個感應器獲取方向數據的例子 * */ package uni.sensor; import android.app.Activity; import android.content.Context; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.os.Bundle; import android.util.Log; public class OrientationActivity extends Activity{ private SensorManager sm; //需要兩個Sensor private Sensor aSensor; private Sensor mSensor; float[] accelerometerValues = new float[3]; float[] magneticFieldValues = new float[3]; private static final String TAG = "sensor"; @Override public void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.main); sm = (SensorManager)getSystemService(Context.SENSOR_SERVICE); aSensor = sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); mSensor = sm.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD); sm.registerListener(myListener, aSensor, SensorManager.SENSOR_DELAY_NORMAL); sm.registerListener(myListener, mSensor,SensorManager.SENSOR_DELAY_NORMAL); //更新顯示數據的方法 calculateOrientation(); } //再次強調:注意activity暫停的時候釋放 public void onPause(){ sm.unregisterListener(myListener); super.onPause(); } final SensorEventListener myListener = new SensorEventListener() { public void onSensorChanged(SensorEvent sensorEvent) { if (sensorEvent.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) magneticFieldValues = sensorEvent.values; if (sensorEvent.sensor.getType() == Sensor.TYPE_ACCELEROMETER) accelerometerValues = sensorEvent.values; calculateOrientation(); } public void onAccuracyChanged(Sensor sensor, int accuracy) {} }; private void calculateOrientation() { float[] values = new float[3]; float[] R = new float[9]; SensorManager.getRotationMatrix(R, null, accelerometerValues, magneticFieldValues); SensorManager.getOrientation(R, values); // 要經過一次數據格式的轉換,轉換為度 values[0] = (float) Math.toDegrees(values[0]); Log.i(TAG, values[0]+""); //values[1] = (float) Math.toDegrees(values[1]); //values[2] = (float) Math.toDegrees(values[2]); if(values[0] >= -5 && values[0] < 5){ Log.i(TAG, "正北"); } else if(values[0] >= 5 && values[0] < 85){ Log.i(TAG, "東北"); } else if(values[0] >= 85 && values[0] <=95){ Log.i(TAG, "正東"); } else if(values[0] >= 95 && values[0] <175){ Log.i(TAG, "東南"); } else if((values[0] >= 175 && values[0] <= 180) || (values[0]) >= -180 && values[0] < -175){ Log.i(TAG, "正南"); } else if(values[0] >= -175 && values[0] <-95){ Log.i(TAG, "西南"); } else if(values[0] >= -95 && values[0] < -85){ Log.i(TAG, "正西"); } else if(values[0] >= -85 && values[0] <-5){ Log.i(TAG, "西北"); } } } 

實訓時間緊張,但抽空寫總結雖然累,收穫卻很多。如果有機會,也想分享第二種更簡單的方法——大家完全可以參考上一篇《Android 基於 Sensor 感應器獲取重力感應加速度的方法》中的程式碼,只要把其中的 Sensor.TYPE_ACCELEROMETER 改成 Sensor.TYPE_ORIENTATION 即可。不過今天分享的這種方法,才是未來 Android 的標準做法,建議大家重點掌握。

Sensor 感應器就先介紹到這裡,接下來該看看進程與線程的內容了。其實 hardware 包裡還有個非常重要的類——Camera 攝像頭,相信大家都聽過 Android 掃描器的強大,以後有機會再和大家分享。後續的安排大概是:線程、Activity,然後是 geocode。

希望本文對大家的 Android 開發有所幫助。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved