Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發 >> 進階開發

Android 定位服務實戰:取得當前位置、追蹤更新與地址反查

編輯:進階開發

Android 內建的位置 API 讓開發者能替應用加上「位置感知」能力,而不必深入研究底層的定位技術細節。在 Google Play 服務的加持下,自動定位追蹤、地理編碼、活動識別等應用情境都能輕鬆實作。

本文從 Location 物件談起,依序說明如何取得當前座標、訂閱週期性的位置更新、控制定位品質,最後把經緯度反查成實際地址,並以一個完整範例收尾。

Location 物件:承載地理位置的資料結構

Location 物件代表一個地理位置,除了必備的緯度與經度,還可能附帶時間戳、海拔、速度與方位角等資訊。以下是使用時最常打交道的成員方法:

序號方法與說明
1float distanceTo(Location dest)
回傳目前位置與指定位置之間的大致距離,單位為公尺。
2float getAccuracy()
取得此位置的估計精準度,單位為公尺。
3double getAltitude()
取得海拔高度(若可用),單位為公尺。
4float getBearing()
取得方位角,單位為度。
5double getLatitude()
取得緯度,單位為度。
6double getLongitude()
取得經度,單位為度。
7float getSpeed()
取得地面速度(若可用),單位為公尺/秒。
8boolean hasAccuracy()
此位置是否帶有精準度資訊。
9boolean hasAltitude()
此位置是否帶有海拔資訊。
10boolean hasBearing()
此位置是否帶有方位角資訊。
11boolean hasSpeed()
此位置是否帶有速度資訊。
12void reset()
清空物件內容。
13void setAccuracy(float accuracy)
設定估計精準度(公尺)。
14void setAltitude(double altitude)
設定海拔(公尺)。
15void setBearing(float bearing)
設定方位角(度)。
16void setLatitude(double latitude)
設定緯度(度)。
17void setLongitude(double longitude)
設定經度(度)。
18void setSpeed(float speed)
設定地面速度(公尺/秒)。
19String toString()
回傳簡潔可讀的描述字串。

取得當前位置

要拿到目前座標,流程是:建立 LocationClient 物件、以 connect() 連上定位服務,再呼叫 getLastLocation()。這個方法會回傳一個 Location 物件,其中含有經緯度以及前述各項資訊。

若要在 Activity 中具備定位能力,必須實作兩個介面:

  • GooglePlayServicesClient.ConnectionCallbacks
  • GooglePlayServicesClient.OnConnectionFailedListener

這兩個介面要求 Activity 類別實作以下回呼方法:

序號回呼方法與說明
1abstract void onConnected(Bundle connectionHint)
與定位服務連線成功時觸發,連線動作由 connect() 發起。
2abstract void onDisconnected()
用戶端斷線時觸發,斷線動作由 disconnect() 發起。
3abstract void onConnectionFailed(ConnectionResult result)
用戶端連線服務失敗時觸發,可從參數取得錯誤碼。
實務上的建議:在 onCreate() 中建立 LocationClient 物件,在 onStart() 中連線,讓定位服務只在 Activity 完全可見期間維持運作;並在 onStop() 中斷線。這樣應用不可見時就不會持續定位,能明顯節省電量。

取得持續的位置更新

如果需要的是「持續追蹤」而不只是單次取點,除了上述兩個介面之外,還要實作 LocationListener。它提供的回呼方法如下:

序號回呼方法與說明
1abstract void onLocationChanged(Location location)
位置發生變化時,LocationClient 會透過此回呼把新位置送給 Activity。

用 LocationRequest 控制定位品質

LocationRequest 物件負責向 LocationClient 描述你希望的更新品質(QoS),透過一組 setter 方法即可微調:

序號方法與說明
1setExpirationDuration(long millis)
設定本次請求的有效期限(毫秒)。
2setExpirationTime(long millis)
以絕對時間設定請求的過期時刻(毫秒)。
3setFastestInterval(long millis)
明確指定位置更新的最快間隔(毫秒)。
4setInterval(long millis)
設定主動位置更新的期望間隔(毫秒)。
5setNumUpdates(int numUpdates)
設定位置更新的次數。
6setPriority(int priority)
設定請求的優先級。

舉例來說,若應用需要高精準度的座標,可用 setPriority(PRIORITY_HIGH_ACCURACY) 搭配 setInterval(5000)。若只需要「城市等級」的粗略位置,可改用 PRIORITY_LOW_POWER 並放大更新間隔;「街區等級」的精度則可考慮 PRIORITY_BALANCED_POWER_ACCURACY。

當 Activity 退到背景(例如進入 onPause())時,應主動移除位置請求,或至少把間隔調大、優先級調降,以降低電力消耗。

把座標轉換成地址

有了經緯度之後,可以用 Geocoder.getFromLocation() 反查對應地址。這個方法是同步的,可能耗時不短,因此應該放在 AsyncTask 的 doInBackground() 中執行。

使用方式是自己繼承 AsyncTask 並覆寫 doInBackground(Params...) 進行背景運算;運算結束後,系統會在 UI 執行緒呼叫 onPostExecute(Result) 讓你更新畫面。啟動任務則是呼叫 execute(Params... params),並把參數傳進去。

下面的範例示範如何以 AsyncTask 完成這件事,讓主要工作不阻塞 UI 執行緒。

完整範例

以下範例展示如何在同一個應用中取得當前位置,並把座標換算成可讀地址。建議使用搭載最新 Android 系統的真機測試,模擬器在定位相關功能上常有落差。

步驟一:安裝 Google Play 服務 SDK

步驟說明
1開啟 SDK Manager:
  • Eclipse(ADT):Window > Android SDK Manager
  • Windows:直接執行 Android SDK 根目錄下的 SDK Manager.exe
  • Mac/Linux:開啟終端機,切換到 Android SDK 的 tools/ 目錄後執行 android 指令
2在套件清單的 Extras 分區找到 Google Play services,若尚未安裝請安裝。安裝後檔案位於 <android-sdk>/extras/google/google_play_services/。
3把 <android-sdk>/extras/google/google_play_services/libproject/google-play-services_lib/ 複製到你存放專案的位置。若使用 Eclipse,透過 File > Import > Android > Existing Android Code into Workspace 瀏覽到 libproject/ 目錄匯入這個函式庫專案。

步驟二:建立 Android 應用

步驟說明
1用 Eclipse 建立專案並命名為 LBSDemo,建置時請把 Target SDK 對到最新版本或較高的 API Level。
2把 Google Play 服務函式庫加入專案設定。
3修改 src/MainActivity.java,加入取得當前位置與反查地址所需的程式碼。
4修改 res/layout/activity_main.xml,加入三個按鈕與兩個文字欄位,分別用來觸發動作與顯示位置/地址。
5修改 res/values/strings.xml,定義所需的字串常數。
6依說明修改 AndroidManifest.xml。
7執行應用,在模擬器或真機上驗證結果。

加入函式庫引用的方式:在專案上按右鍵,選擇 Build Path > Configure Build Path > Android,點「Add」按鈕後雙擊 google-play-services_lib 選項即可。

主活動檔案 src/com.yiibai.lbsdemo/MainActivity.java:

package com.example.lbsdemo;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.location.LocationClient;

import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends FragmentActivity implements
        GooglePlayServicesClient.ConnectionCallbacks,
        GooglePlayServicesClient.OnConnectionFailedListener {

    LocationClient mLocationClient;
    private TextView addressLabel;
    private TextView locationLabel;
    private Button getLocationBtn;
    private Button disconnectBtn;
    private Button connectBtn;

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

        locationLabel = (TextView) findViewById(R.id.locationLabel);
        addressLabel = (TextView) findViewById(R.id.addressLabel);

        getLocationBtn = (Button) findViewById(R.id.getLocation);
        getLocationBtn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                displayCurrentLocation();
            }
        });

        disconnectBtn = (Button) findViewById(R.id.disconnect);
        disconnectBtn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                mLocationClient.disconnect();
                locationLabel.setText("Got disconnected....");
            }
        });

        connectBtn = (Button) findViewById(R.id.connect);
        connectBtn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                mLocationClient.connect();
                locationLabel.setText("Got connected....");
            }
        });

        // Create the LocationRequest object
        mLocationClient = new LocationClient(this, this, this);
    }

    @Override
    protected void onStart() {
        super.onStart();
        // Connect the client.
        mLocationClient.connect();
        locationLabel.setText("Got connected....");
    }

    @Override
    protected void onStop() {
        // Disconnect the client.
        mLocationClient.disconnect();
        super.onStop();
        locationLabel.setText("Got disconnected....");
    }

    @Override
    public void onConnected(Bundle dataBundle) {
        Toast.makeText(this, "Connected", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onDisconnected() {
        Toast.makeText(this, "Disconnected. Please re-connect.", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        Toast.makeText(this, "Connection Failure : " + connectionResult.getErrorCode(),
                Toast.LENGTH_SHORT).show();
    }

    public void displayCurrentLocation() {
        // Get the current location's latitude & longitude
        Location currentLocation = mLocationClient.getLastLocation();
        String msg = "Current Location: "
                + Double.toString(currentLocation.getLatitude()) + ","
                + Double.toString(currentLocation.getLongitude());

        locationLabel.setText(msg);

        // To display the current address in the UI
        (new GetAddressTask(this)).execute(currentLocation);
    }

    /*
     * Following is a subclass of AsyncTask which has been used to get
     * address corresponding to the given latitude & longitude.
     */
    private class GetAddressTask extends AsyncTask<Location, Void, String> {

        Context mContext;

        public GetAddressTask(Context context) {
            super();
            mContext = context;
        }

        /* When the task finishes, onPostExecute() displays the address. */
        @Override
        protected void onPostExecute(String address) {
            addressLabel.setText(address);
        }

        @Override
        protected String doInBackground(Location... params) {
            Geocoder geocoder = new Geocoder(mContext, Locale.getDefault());

            Location loc = params[0];
            List<Address> addresses = null;

            try {
                addresses = geocoder.getFromLocation(loc.getLatitude(), loc.getLongitude(), 1);
            } catch (IOException e1) {
                Log.e("LocationSampleActivity", "IO Exception in getFromLocation()");
                e1.printStackTrace();
                return ("IO Exception trying to get address");
            } catch (IllegalArgumentException e2) {
                String errorString = "Illegal arguments "
                        + Double.toString(loc.getLatitude()) + " , "
                        + Double.toString(loc.getLongitude())
                        + " passed to address service";
                Log.e("LocationSampleActivity", errorString);
                e2.printStackTrace();
                return errorString;
            }

            if (addresses != null && addresses.size() > 0) {
                Address address = addresses.get(0);
                String addressText = String.format(
                        "%s, %s, %s",
                        address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "",
                        address.getLocality(),
                        address.getCountryName());
                return addressText;
            } else {
                return "No address found";
            }
        }
    } // AsyncTask class
}

版面配置 res/layout/activity_main.xml:

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

    <Button
        android:id="@+id/getLocation"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/get_location"/>

    <Button
        android:id="@+id/disconnect"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/disconnect"/>

    <Button
        android:id="@+id/connect"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/connect"/>

    <TextView
        android:id="@+id/locationLabel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

    <TextView
        android:id="@+id/addressLabel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

</LinearLayout>

小結

整條脈絡其實很單純:建立 LocationClient、連線、取點或訂閱更新,最後視需要把座標交給 Geocoder 反查地址。真正需要花心思的地方在於優先級與更新頻率的取捨——精準度與電量永遠是一組需要權衡的參數。

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