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

Android 方向感應器實作電子指南針:SensorManager 與 RotateAnimation

編輯:關於 Android 程式設計

指南針是入門感應器開發最經典的範例。原理並不複雜:讀取方向感應器(Orientation Sensor)回報的角度值,再用旋轉動畫即時轉動指針圖片,讓它永遠指向北方。

Step 1:建立專案並準備素材

新增一個名為 Compass 的專案,把指南針圖片放進 res/drawable-hdpi 目錄。

Step 2:設計版面 main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:gravity="center"
>
    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/compass"
        android:id="@+id/imageView"
    />
</LinearLayout>

Step 3:MainActivity 取得感應器並驅動動畫

public class MainActivity extends Activity {
    private ImageView imageView;
    /** 感應器管理器 */
    private SensorManager manager;
    private SensorListener listener = new SensorListener();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        imageView = (ImageView) this.findViewById(R.id.imageView);
        imageView.setKeepScreenOn(true);      // 保持螢幕不熄
        // 取得系統服務 SENSOR_SERVICE,回傳 SensorManager
        manager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
    }

    @Override
    protected void onResume() {
        // 取得方向感應器
        Sensor sensor = manager.getDefaultSensor(Sensor.TYPE_ORIENTATION);
        // 應用回到前台時註冊監聽器
        manager.registerListener(listener, sensor,
                SensorManager.SENSOR_DELAY_GAME);
        super.onResume();
    }

    @Override
    protected void onPause() {
        // 離開前台時務必取消註冊,避免耗電
        manager.unregisterListener(listener);
        super.onPause();
    }

    private final class SensorListener implements SensorEventListener {
        private float predegree = 0;

        @Override
        public void onSensorChanged(SensorEvent event) {
            /*
             * values[0]: x 軸方向的角度(方位角)
             * values[1]: y 軸方向的俯仰
             * values[2]: z 軸方向的滾轉
             */
            float degree = event.values[0];

            RotateAnimation animation = new RotateAnimation(
                    predegree, degree,
                    Animation.RELATIVE_TO_SELF, 0.5f,
                    Animation.RELATIVE_TO_SELF, 0.5f);
            animation.setDuration(200);
            imageView.startAnimation(animation);
            predegree = -degree;
        }

        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) { }
    }
}

Step 4:AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="cn.roco.sensor"
    android:versionCode="1"
    android:versionName="1.0">
    <uses-sdk android:minSdkVersion="8" />
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name="MainActivity"
            android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

幾個關鍵細節

  • 動畫中心點:RELATIVE_TO_SELF, 0.5f 代表以圖片自身中心為旋轉軸,這是指南針動畫自然的關鍵。
  • 角度連續性:範例用 predegree = -degree 承接上一幀角度,讓動畫有連續感;實務上更好用的做法是處理「359° 跳到 1°」的跨界問題,把差值正規化到 -180~180 之間,指針才不會整圈狂轉。
  • 感應器生命週期:一定要在 onResume 註冊、onPause 取消註冊,否則背景仍持續取樣會明顯耗電。
  • TYPE_ORIENTATION 已被淘汰:新版 Android 建議改用 TYPE_ACCELEROMETER 與 TYPE_MAGNETIC_FIELD 兩者透過 SensorManager.getRotationMatrixFromVector/getOrientation 組合成方位角,精度與相容性都更好。若要判斷是否有磁場感應器,也可用 hasSystemFeature(SensorManager.SENSOR_SERVICE) 相關檢查提前處理。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved