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

Android 指南針實作:用方向感測器驅動指針旋轉

編輯:關於 Android 程式設計

指南針看起來神奇,原理其實很單純:讀取方向感測器(Orientation Sensor)回報的角度,再讓指針圖片轉到對應角度。

一、版面配置

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:gravity="center"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/zn" />
</LinearLayout>

一張指針圖片就夠了。這裡用的素材如下:

二、MainActivity.java

package com.example.compass;

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.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;

public class MainActivity extends Activity {

    private ImageView imageView;
    private SensorManager manager;
    private final 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);

        manager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
    }

    @Override
    protected void onResume() {
        super.onResume();
        Sensor sensor = manager.getDefaultSensor(Sensor.TYPE_ORIENTATION);
        manager.registerListener(listener, sensor, SensorManager.SENSOR_DELAY_GAME);
    }

    @Override
    protected void onPause() {
        manager.unregisterListener(listener);
        super.onPause();
    }

    private final class SensorListener implements SensorEventListener {

        private float predegree = 0;

        public void onSensorChanged(SensorEvent event) {
            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;
        }

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

三、執行結果

四、幾個關鍵細節

1. 感測器要在 onResume 註冊、onPause 取消註冊

這不是風格問題,而是電池壽命問題。感測器一旦註冊就會持續消耗電力,App 退到背景時若不取消註冊,會明顯縮短待機時間。這條規則適用於所有系統感測器。

2. 為什麼要取負號(-degree)

感測器回報的角度與我們期待的視覺方向是相反的:裝置順時針轉時,指針在畫面上應該看起來是逆時針轉(因為指針指向的是北方,而不是裝置朝向)。加上負號就是把這個關係反轉回來。

3. 用 predegree 做動畫銜接

每次旋轉動畫的起點是「上一帧的角度」,終點是「這一帧的角度」,這樣動畫才會連續而不跳動。如果每次都從 0 開始轉,畫面會不斷閃回原位。

4. 角度跨越 0/360 邊界時會「反轉一圈」

這是實作指南針最經典的 bug:當角度從 359° 變成 1° 時,程式會算出「要轉 -358°」,指針就會瘋狂地繞一圈。解法是對差值做正規化:

float delta = degree - predegree;
// 把差值限制在 -180 ~ 180 之間
while (delta > 180) delta -= 360;
while (delta < -180) delta += 360;

RotateAnimation animation = new RotateAnimation(
        predegree, predegree - delta,
        Animation.RELATIVE_TO_SELF, 0.5f,
        Animation.RELATIVE_TO_SELF, 0.5f);

5. TYPE_ORIENTATION 已被淘汰

Sensor.TYPE_ORIENTATION 在 Android 2.2(API 8)就已被標記為 deprecated。現代做法是改讀以下兩種感測器之一:

  • TYPE_ACCELEROMETER + TYPE_MAGNETIC_FIELD:透過 SensorManager.getRotationMatrixFromVector() 與 getOrientation() 自行計算方位角。
  • TYPE_ROTATION_VECTOR(API 9+):融合感測器,直接回報裝置姿態,精度與穩定性都更好,是目前的首選。

另外別忘了,指南針需要用到磁力計,使用前應檢查裝置是否具備該硬體:

Sensor magnetic = manager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
if (magnetic == null) {
    // 此裝置不支援指南針功能
}

6. 現場若有強磁場或電子設備,讀數會嚴重失真

磁力計極易受干擾。實務上可以監聽 onAccuracyChanged(),當 SENSOR_STATUS_UNRELIABLE 時提示使用者「請遠離磁鐵與電子設備並做 8 字校準」。

把這幾點補上,一個指南針就不只是能轉,而是轉得準、轉得順、也不吃電。

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