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

Android 定位入門:LocationManager 取得座標的完整流程

編輯:關於 Android 程式設計

Android 之所以在行動應用上特別強大,很大一部分來自它對硬體能力的封裝。定位就是最典型的一項:你只要透過系統服務 LocationManager,就能拿到裝置目前所在的經緯度與海拔,而不必去操心底層是走 GPS 晶片還是基站三角定位。

一、取得 LocationManager 實例

所有定位相關的操作都從系統服務開始,用 getSystemService 拿到 LocationManager,接著註冊位置更新,最後讀取一次「最後已知位置」作為初始值。

LocationManager locationManager = (LocationManager)
        getSystemService(LOCATION_SERVICE);

// 每 10000 毫秒更新一次,且忽略 0 公尺以內的位移
locationManager.requestLocationUpdates(
        LocationManager.GPS_PROVIDER, 10000, 0, locationListener);

Location location = locationManager.getLastKnownLocation(
        LocationManager.GPS_PROVIDER);

String latitude  = Double.toString(location.getLatitude());
String longitude = Double.toString(location.getLongitude());
String altitude  = Double.toString(location.getAltitude());

TextView tv = (TextView) findViewById(R.id.local);
tv.setText("latitude:" + latitude + " longitude:" + longitude
        + " altitude:" + altitude);

requestLocationUpdates 的第二、三個參數分別是「最小時間間隔」與「最小位移間隔」,最後一個參數則是接收回呼的 LocationListener。把時間間隔調小會讓定位更即時,但也更耗電,實務上需要權衡。

二、實作 LocationListener 的四個回呼

private final LocationListener locationListener = new LocationListener() {

    // 座標改變時觸發;若 Provider 回報的是同一組座標則不會觸發
    public void onLocationChanged(Location location) {
        if (location != null) {
            String latitude  = Double.toString(location.getLatitude());
            String longitude = Double.toString(location.getLongitude());
            String altitude  = Double.toString(location.getAltitude());

            TextView tv = (TextView) findViewById(R.id.local);
            tv.setText("latitude:" + latitude + " longitude:"
                    + longitude + " altitude:" + altitude);
        }
    }

    // Provider 被關閉時觸發,例如使用者關掉 GPS
    public void onProviderDisabled(String provider) { }

    // Provider 被開啟時觸發,例如使用者打開 GPS
    public void onProviderEnabled(String provider) { }

    // Provider 狀態在「可用 / 暫時不可用 / 無服務」之間切換時觸發
    public void onStatusChanged(String provider, int status, Bundle extras) { }
};

三、權限宣告

別忘了在 AndroidManifest.xml 加上定位權限,否則執行期會直接拿到空值或丟出安全性例外:

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

四、在模擬器上測試

沒有實機時,可以用 ADT 提供的 Emulator Control 檢視(Window → Show View 中開啟)手動送一組座標,或載入 KML/GPX 檔案回放一段軌跡。

另一條路是走 telnet:先開命令列執行 telnet 5554,進入後輸入:

geo fix -39.4 116.9 326

三個參數依序是經度、緯度、海拔,其中海拔可以省略。送出後,App 端就會收到一次位置更新,整個定位流程於是可以在沒有 GPS 模組的開發環境裡完整跑通。

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