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

用方向傳感器實現 Android 電子指南針

編輯:關於 Android 程式設計

電子指南針的原理並不複雜:讀取設備的方向傳感器拿到方位角,再驅動一張指針圖片旋轉即可。本文用不到五十行代碼完成這個效果。

一、布局文件

界面只有一個居中的 ImageView,顯示指南針的表盤圖片。

<?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

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 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() {
        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;

        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) {
        }
    }
}

運行效果

幾處值得留意的細節

傳感器的註冊與卸載必須成對出現。示例把它們放在 onResume 與 onPause 中,這是最合適的位置——頁面不可見時停止採集,既省電又能避免頁面銷毀後仍持有監聽而洩露。SENSOR_DELAY_GAME 是較快的採樣頻率,如果只做指南針這種變化平緩的展示,用 SENSOR_DELAY_UI 已經足夠,也更省電。

動畫起點要記住上一次的角度。這就是 predegree 的作用:RotateAnimation 的第一個參數是起始角度,每次都從 0 開始轉會導致指針反覆歸零。同時注意角度取負號——傳感器返回的方位角與界面順時針旋轉方向相反,不加負號指針會朝錯誤的方向轉。

旋轉中心設為 0.5f, 0.5f,即繞圖片中心旋轉,這是指南針應有的視覺表現。

最後需要說明的是,TYPE_ORIENTATION 傳感器在 Android 2.3 起已被廢棄。新項目應改用 TYPE_ACCELEROMETER 與 TYPE_MAGNETIC_FIELD 兩個傳感器,通過 SensorManager.getRotationMatrix() 與 getOrientation() 計算方位角。同時由於指南針依賴磁力計,使用前最好檢測設備是否具備該硬件,並在使用時提示用戶遠離磁鐵與金屬物體以減少干擾。

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