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

高分段進階攻略(5):用方向感測器做電子指南針

編輯:關於 Android 程式設計

先前有网友私信問:做過磁場感測器,能做出指南針嗎?其實在第一篇就提過,磁場感測器做得到,只是演算法麻煩得多。最簡便的指南針可以用方向感測器實作。一直忙到現在才有空寫這篇,先上圖:

原理

版面配置很簡單,就一張指南針的平面圖:

<ImageView
    android:id="@+id/main_iv"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:src="@drawable/bg" />

演算法在上一篇也提過:values[0] 代表方位角,也就是手機繞 Z 軸旋轉的角度。0 表示北(North),90 表示東(East),180 表示南(South),270 表示西(West)。當手機水平放置且 values[0] 剛好落在這四個值上,代表手機正前方就對應 those 方向——這正是電子羅盤的基礎。

因此思路很直白:拿到 values[0],再把指針圖片反向旋轉同樣的角度,指針就會永遠指向真北。

核心:onSensorChanged

public void onSensorChanged(SensorEvent event) {
    if (event.sensor.getType() == Sensor.TYPE_ORIENTATION) {
        // 取得繞 Z 軸旋轉的角度
        float degree = event.values[0];

        // 建立旋轉動畫(反向轉過 degree 度)
        RotateAnimation ra = new RotateAnimation(
                currentDegree, -degree,
                Animation.RELATIVE_TO_SELF, 0.5f,
                Animation.RELATIVE_TO_SELF, 0.5f);

        ra.setDuration(200);
        ra.setFillAfter(true); // 動畫結束後保留狀態
        image.startAnimation(ra);

        currentDegree = -degree;
    }
}

用 currentDegree 記錄目前角度、動畫只做差值旋轉,可以避免指針每帧都從 0 開始轉而產生的跳動。

完整程式碼

public class OrientationActivity extends Activity implements SensorEventListener {

    private TextView tv_context;
    private Sensor mAccelerometer;
    private SensorManager mSensorManager;
    private float currentDegree = 0f;   // 記錄指南針圖片轉過的角度
    private ImageView image;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_orien);
        infoViews();
    }

    private void infoViews() {
        tv_context = (TextView) findViewById(R.id.tv_context);
        tv_context.setText("指南針");
        mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION);
        image = (ImageView) findViewById(R.id.main_iv);
    }

    @Override
    protected void onResume() {
        if (mAccelerometer != null) {
            mSensorManager.registerListener(this, mAccelerometer,
                    SensorManager.SENSOR_DELAY_NORMAL);
            Toast.makeText(getApplicationContext(), "此裝置有方向感測器", 0).show();
        } else {
            Toast.makeText(getApplicationContext(), "此裝置沒有方向感測器", 0).show();
        }
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mSensorManager.unregisterListener(this); // 記得反註冊,否則耗電
    }

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

    @Override
    public void onSensorChanged(SensorEvent event) {
        if (event.sensor.getType() == Sensor.TYPE_ORIENTATION) {
            float degree = event.values[0];
            RotateAnimation ra = new RotateAnimation(currentDegree, -degree,
                    Animation.RELATIVE_TO_SELF, 0.5f,
                    Animation.RELATIVE_TO_SELF, 0.5f);
            ra.setDuration(200);
            ra.setFillAfter(true);
            image.startAnimation(ra);
            currentDegree = -degree;
        }
    }
}

若要進一步優化

需要更精細的定位資訊時,可以改用 Criteria 挑選合適的 location provider:

LocationManager locationManager =
        (LocationManager) getSystemService(Context.LOCATION_SERVICE);

Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);       // 最高精度
criteria.setAltitudeRequired(false);              // 不需要海拔
criteria.setBearingRequired(false);               // 不需要方位
criteria.setCostAllowed(true);                    // 允許付費來源
criteria.setPowerRequirement(Criteria.POWER_LOW); // 低耗電

Location location = locationManager.getLastKnownLocation(
        locationManager.getBestProvider(criteria, true));

再以 LocationListener 接收更新:

LocationListener listener = new LocationListener() {
    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        if (status != LocationProvider.OUT_OF_SERVICE) {
            updateLocation(mLocationManager.getLastKnownLocation(mLocationProvider));
        } else {
            mLocationTextView.setText(R.string.cannot_get_location);
        }
    }

    @Override public void onProviderEnabled(String provider) { }
    @Override public void onProviderDisabled(String provider) { }

    @Override
    public void onLocationChanged(Location location) {
        updateLocation(location);
    }
};

兩個實務提醒

第一,TYPE_ORIENTATION 在 API 8 之後已被標示為 deprecated。新專案建議改用 TYPE_ACCELEROMETER 搭配 TYPE_MAGNETIC_FIELD,透過 SensorManager.getRotationMatrix() 與 getOrientation() 自行計算方位角,這樣在愈來愈多新機上都能穩定運作。

第二,寫的過程中我一直有個疑問:values[0] 是從一開始就綁好東南西北的嗎?否則怎麼可能一啟動就指向北?這部分牽涉到感測器座標系與裝置出廠校準的關係,若有清楚答案歡迎指教。

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