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

Android GPS 定位實戰:即時取得經緯度、海拔、速度與方位

編輯:關於 Android 程式設計

先前的文章已經介紹過 GPS 的基本概念,以及 Android 開發定位功能時常用的類別與方法。這一篇我們直接動手做一個小應用:讓畫面即時顯示使用者目前的位置資訊,包含緯度、經度、高度、移動方向與速度。

Activity 實作

核心只有三件事:取得系統的 LocationManager、先讀一次最近的位置、再註冊位置變更的監聽器。

package comhome.location;

import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.EditText;

public class LocationTestActivity extends Activity {

    private LocationManager locationManager;
    private EditText show;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        show = (EditText) findViewById(R.id.main_et_show);

        // 取得系統的定位服務
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        // 先取最近一次已知的位置,讓畫面不至于空白
        Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        updateView(location);

        // 每 2 秒、位移超過 8 公尺就回報一次
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 8,
                new LocationListener() {

            @Override
            public void onLocationChanged(Location location) {
                // 位置改變時更新畫面
                updateView(location);
            }

            @Override
            public void onProviderDisabled(String provider) {
                updateView(null);
            }

            @Override
            public void onProviderEnabled(String provider) {
                updateView(locationManager.getLastKnownLocation(provider));
            }

            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {
            }
        });
    }

    private void updateView(Location location) {
        if (location != null) {
            StringBuffer sb = new StringBuffer();
            sb.append("即時的位置資訊:\n經度:").append(location.getLongitude());
            sb.append("\n緯度:").append(location.getLatitude());
            sb.append("\n高度:").append(location.getAltitude());
            sb.append("\n速度:").append(location.getSpeed());
            sb.append("\n方向:").append(location.getBearing());
            sb.append("\n精度:").append(location.getAccuracy());
            show.setText(sb.toString());
        } else {
            // 傳入的 Location 為 null 時清空欄位
            show.setText("");
        }
    }
}

版面配置

這裡用一個不可編輯的 EditText 當作純文字輸出區,好處是換行與長文字顯示都方便。

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <EditText
        android:id="@+id/main_et_show"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:cursorVisible="false"
        android:editable="false" />

</LinearLayout>

權限宣告

沒有權限的話 getLastKnownLocation 只會拿到 null,這是最常見的「定位沒反應」原因。

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

若同時要支援基地台與網路定位,可以再加上 ACCESS_COARSE_LOCATION。另外從 Android 6.0 開始,定位屬於「危險權限」,除了宣告之外還必須在執行期動態向使用者請求核准。

幾個實務上的眉角

requestLocationUpdates 的第二、三個參數分別是「最小時間間隔(毫秒)」與「最小位移距離(公尺)」。兩者並非硬性保證,系統會依實際條件與電量考量決定回報頻率;把數值調得太激進只會白白消耗電力。

另外別忘了在 onPause() 或不需要定位時呼叫 removeUpdates() 取消註冊,否則監聽器會持續被持有,容易導致 Activity 無法回收。

實際執行的畫面如下:

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