本文示範如何以 Eclipse 為開發環境,完成一個具備 Google Map 與 GPS 定位能力的 Android 應用,從環境建置、SDK 與 ADT 嵌入、專案建立、API Key 申請,一路到打包發佈 apk。
1)下載:Oracle 官方 Java SE 下載頁(本案例使用 jdk5.0)。
2)安裝:預設安裝即可。
3)部署: 【我的電腦】→右鍵→【屬性】→【進階】→【環境變數】,設定:
JAVA_HOME = C:/Program Files/Java/jdk1.5.0_02 /* jdk 安裝路徑 */ CLASSPATH = %JAVA_HOME%/lib Path 增加:%JAVA_HOME%/bin
下載點為 eclipse.org 官方下載頁(本案例使用 eclipse 3.6.2),解壓縮即可。啟動 eclipse.exe 後,進入【Window】→【Preferences】→【Java】檢查 JRE 安裝,若沒有則手動設定路徑。
下載後啟動 Eclipse,選擇【Help】→【Install New Software...】,在介面中填入 ADT 解壓路徑,再按下一步安裝(本案例安裝 ADT 8.0.0)。
1)解壓 SDK 套件。
2)啟動 Eclipse,選擇【Window】→【Preferences】→【Android】,把 "SDK Location" 設為 SDK 解壓目錄。
3)選擇【Window】→【Android SDK and AVD Manager】,安裝需要的 SDK 版本並建立 AVD(本案例安裝 sdk 2.2、API 8)。至此 Eclipse 已可開發 Android。
4)若要開發手機定位,還需在【Android SDK and AVD Manager】中安裝 Google API,本案例安裝與 SDK 同版本的 API 8 Google API。
1. 建立名為 mapdemo 的專案,套件名稱取 cn.map,Activity 命名為 GMapsActivity。
2. AndroidManifest.xml 設定:
<uses-library android:name="com.google.android.maps" /> /* 放在 application 內 */ <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> /* 以上三項放在 application 外 */
3. main.xml 設定:加入 MapView 元件。
<com.google.android.maps.MapView
android:id="@+id/MapView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:apiKey="你的 API Key"
/>
其中 android:apiKey 需要自行申請,流程如下:
1)找出 debug.keystore 路徑:【Window】→【Preferences】→【Android】→【Build】頁的 default debug keystore 欄位即為該路徑。
2)找出 Java 的 keytool 工具:%JAVA_HOME%/bin 下的 keytool.exe。
3)產生 MD5:在 cmd 下切換到 debug.keystore 所在目錄,執行 keytool -list -keystore debug.keystore,提示輸入密碼時輸入預設的 android,即可取得 MD5 值。
4)到 Google Maps API 簽章頁面輸入 MD5 取得 API Key,填回 main.xml。
package cn.map;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.widget.Toast;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import java.util.List;
import android.content.Context;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Point;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapController;
import com.google.android.maps.Overlay;
public class GMapsActivity extends MapActivity {
private MapView mMapView;
private MapController mMapController;
private GeoPoint mGeoPoint;
double latitude, longitude;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mMapView = (MapView) findViewById(R.id.MapView1);
mMapView.setTraffic(true); // 交通模式
//mMapView.setSatellite(true); // 衛星模式
//mMapView.setStreetView(false); // 街景模式
mMapController = mMapView.getController(); // 取得控制 MapView 的物件
mMapView.setEnabled(true);
mMapView.setClickable(true);
mMapView.setBuiltInZoomControls(true); // 支援縮放
mGeoPoint = new GeoPoint((int)(23 * 1000000), (int)(113 * 1000000)); // 起點設為廣州
mMapController.animateTo(mGeoPoint); // 定位到指定座標
mMapController.setZoom(12); // 倍數 1-21
// 加入 Overlay 以顯示標註資訊
MyLocationOverlay myLocationOverlay = new MyLocationOverlay();
List<Overlay> list = mMapView.getOverlays();
list.add(myLocationOverlay);
// 透過 GPS 取得座標
openGPSSettings();
getLocation();
}
protected boolean isRouteDisplayed()
{
return false;
}
class MyLocationOverlay extends Overlay
{
@Override
public boolean draw(Canvas canvas, MapView mapView, boolean shadow, long when)
{
super.draw(canvas, mapView, shadow);
Paint paint = new Paint();
Point myScreenCoords = new Point();
// 將經緯度轉換成實際螢幕座標
mapView.getProjection().toPixels(mGeoPoint, myScreenCoords);
paint.setStrokeWidth(1);
paint.setARGB(255, 255, 0, 0);
paint.setStyle(Paint.Style.STROKE);
canvas.drawText("廣州歡迎你", myScreenCoords.x, myScreenCoords.y, paint);
return true;
}
}
private void openGPSSettings() {
LocationManager alm = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
if (alm.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)) {
Toast.makeText(this, "GPS 模組正常", Toast.LENGTH_SHORT).show();
return;
}
Toast.makeText(this, "請開啟 GPS!", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Settings.ACTION_SECURITY_SETTINGS);
startActivityForResult(intent, 0); // 設定完成後返回取得介面
}
private final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// 座標改變時觸發;若 Provider 傳入相同座標則不會觸發
if (location != null) {
latitude = location.getLatitude(); // 緯度
longitude = location.getLongitude(); // 經度
mGeoPoint = new GeoPoint((int) latitude, (int) longitude);
mMapController.animateTo(mGeoPoint); // 定位到指定座標
mMapController.setZoom(12); // 倍數 1-21
}
}
public void onProviderDisabled(String provider) {
// Provider 被關閉時觸發,例如 GPS 被 disable
}
public void onProviderEnabled(String provider) {
// Provider 被打開時觸發
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// 狀態在可用、暫時不可用、無服務之間切換時觸發
}
};
private void getLocation(){
// 取得位置管理服務
LocationManager locationManager;
String serviceName = Context.LOCATION_SERVICE;
locationManager = (LocationManager) this.getSystemService(serviceName);
// 建立搜尋條件
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE); // 高精度
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW); // 低功耗
String provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
mGeoPoint = new GeoPoint((int) latitude, (int) longitude);
mMapController.animateTo(mGeoPoint);
mMapController.setZoom(12);
}
// 設定監聽器:最小更新間隔 100 秒、最小位移 500 公尺
locationManager.requestLocationUpdates(provider, 100 * 1000, 500, locationListener);
}
}
【Export】→【Android】或【Android Tools】→【Export unsigned / signed Application package】,依步驟即可產出 apk。關鍵在於重新產生正式 API Key:
1. 產生正式 keystore:【Android Tools】→【Export signed Application package】,步驟二選 "create new keystore",例如 Location=D:/android/workspace/mapdemo.keystore、Password=mapdemo;步驟三填入 alias=mymapdemo、Password=mapdemo 等資訊,最後產生 apk。此時的 apk 還不能發佈,必須換上正式 API Key。
2. 取得 MD5 與 API Key:在 cmd 下切到 D:/android/workspace,執行 keytool –list –keystore mapdemo.keystore,輸入密碼 mapdemo 後取得 MD5,再到 Google Maps API 簽章頁換取正式 android:apiKey,並修改 main.xml 中原本由 debug.keystore 產生的 Key。
3. 重新發佈:再次【Android Tools】→【Export signed Application package】,步驟二與步驟三都選 "Use existing keystore",指定 mapdemo.keystore 與 alias mymapdemo,最後產生的 apk 即可對外發佈。
說明:本文流程在模擬器上可正常顯示地圖;真機移動時的 GPS 定位未經完整實測。實測 android 2.1 手機提示解析套件出錯,android 2.2 手機則安裝成功,與開發所用的 SDK 2.2 版本一致。
提醒:Google Maps Android API v1 與其 Key 申請服務早已停止,現行專案請改用 Maps SDK for Android(v2 以上)搭配 Google Play services,並以 SHA-1 憑證指紋申請 Key。