編輯:進階開發
Android 內建的位置 API 讓開發者能替應用加上「位置感知」能力,而不必深入研究底層的定位技術細節。在 Google Play 服務的加持下,自動定位追蹤、地理編碼、活動識別等應用情境都能輕鬆實作。
本文從 Location 物件談起,依序說明如何取得當前座標、訂閱週期性的位置更新、控制定位品質,最後把經緯度反查成實際地址,並以一個完整範例收尾。
Location 物件代表一個地理位置,除了必備的緯度與經度,還可能附帶時間戳、海拔、速度與方位角等資訊。以下是使用時最常打交道的成員方法:
| 序號 | 方法與說明 |
|---|---|
| 1 | float distanceTo(Location dest)回傳目前位置與指定位置之間的大致距離,單位為公尺。 |
| 2 | float getAccuracy()取得此位置的估計精準度,單位為公尺。 |
| 3 | double getAltitude()取得海拔高度(若可用),單位為公尺。 |
| 4 | float getBearing()取得方位角,單位為度。 |
| 5 | double getLatitude()取得緯度,單位為度。 |
| 6 | double getLongitude()取得經度,單位為度。 |
| 7 | float getSpeed()取得地面速度(若可用),單位為公尺/秒。 |
| 8 | boolean hasAccuracy()此位置是否帶有精準度資訊。 |
| 9 | boolean hasAltitude()此位置是否帶有海拔資訊。 |
| 10 | boolean hasBearing()此位置是否帶有方位角資訊。 |
| 11 | boolean hasSpeed()此位置是否帶有速度資訊。 |
| 12 | void reset()清空物件內容。 |
| 13 | void setAccuracy(float accuracy)設定估計精準度(公尺)。 |
| 14 | void setAltitude(double altitude)設定海拔(公尺)。 |
| 15 | void setBearing(float bearing)設定方位角(度)。 |
| 16 | void setLatitude(double latitude)設定緯度(度)。 |
| 17 | void setLongitude(double longitude)設定經度(度)。 |
| 18 | void setSpeed(float speed)設定地面速度(公尺/秒)。 |
| 19 | String toString()回傳簡潔可讀的描述字串。 |
要拿到目前座標,流程是:建立 LocationClient 物件、以 connect() 連上定位服務,再呼叫 getLastLocation()。這個方法會回傳一個 Location 物件,其中含有經緯度以及前述各項資訊。
若要在 Activity 中具備定位能力,必須實作兩個介面:
GooglePlayServicesClient.ConnectionCallbacksGooglePlayServicesClient.OnConnectionFailedListener這兩個介面要求 Activity 類別實作以下回呼方法:
| 序號 | 回呼方法與說明 |
|---|---|
| 1 | abstract void onConnected(Bundle connectionHint)與定位服務連線成功時觸發,連線動作由 connect() 發起。 |
| 2 | abstract void onDisconnected()用戶端斷線時觸發,斷線動作由 disconnect() 發起。 |
| 3 | abstract void onConnectionFailed(ConnectionResult result)用戶端連線服務失敗時觸發,可從參數取得錯誤碼。 |
實務上的建議:在onCreate()中建立 LocationClient 物件,在onStart()中連線,讓定位服務只在 Activity 完全可見期間維持運作;並在onStop()中斷線。這樣應用不可見時就不會持續定位,能明顯節省電量。
如果需要的是「持續追蹤」而不只是單次取點,除了上述兩個介面之外,還要實作 LocationListener。它提供的回呼方法如下:
| 序號 | 回呼方法與說明 |
|---|---|
| 1 | abstract void onLocationChanged(Location location)位置發生變化時,LocationClient 會透過此回呼把新位置送給 Activity。 |
LocationRequest 物件負責向 LocationClient 描述你希望的更新品質(QoS),透過一組 setter 方法即可微調:
| 序號 | 方法與說明 |
|---|---|
| 1 | setExpirationDuration(long millis)設定本次請求的有效期限(毫秒)。 |
| 2 | setExpirationTime(long millis)以絕對時間設定請求的過期時刻(毫秒)。 |
| 3 | setFastestInterval(long millis)明確指定位置更新的最快間隔(毫秒)。 |
| 4 | setInterval(long millis)設定主動位置更新的期望間隔(毫秒)。 |
| 5 | setNumUpdates(int numUpdates)設定位置更新的次數。 |
| 6 | setPriority(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 系統的真機測試,模擬器在定位相關功能上常有落差。
| 步驟 | 說明 |
|---|---|
| 1 | 開啟 SDK Manager:
|
| 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/ 目錄匯入這個函式庫專案。 |
| 步驟 | 說明 |
|---|---|
| 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 反查地址。真正需要花心思的地方在於優先級與更新頻率的取捨——精準度與電量永遠是一組需要權衡的參數。
先睹為快:Android 3.0 細節曝光
國外網站 Phandroid 近日披露了 Android 3.0(Gingerbread)的一些細節。雖然系統仍在開發中,但從這些曝光的畫面已能看出方向:外觀更順滑,視覺
Android 開發入門(2):SDK 裝好之後,動手寫第一支程式
官方下載頁是 developer.android.com/sdk/installing.html(當時在大陸被牆)。下載後解壓,例如放到 /home/chen/下載/an
Android 與 Linux 的裂痕:授權之爭與開源社群的質疑
Android 包含一個核心庫,提供了 Java 語言核心庫的大部分功能。而論與 Linux 的距離,它比 Mac OS 之於 Linux 還要遠——這樣的形容並不誇張。
Android 開發入門教程(五):讓 TextView 出現在螢幕上
Activity 本身是 Context 的子類,所以它也是一個 Context,這就是為什麼我們能在 TextView 的建構子裡直接寫 this。 設定要顯示的文字