編輯:Android 開發實例
地圖功能在 Android 上有過幾種做法,各自的限制值得先弄清楚,否則很容易在專案中期才發現路走錯了。
MapView + MapActivity:想使用 MapView,Activity 就必須繼承 MapActivity,這會直接吃掉繼承結構,在需要多層繼承時非常綁手。而且官方已明確宣布第一版 API 停止維護:
Version 1 of the Google Maps Android API has been officially deprecated as of December 3rd, 2012. From March 3rd, 2013 you will no longer be able to request an API key for this version. No new features will be added. Apps using v1 will continue to work on devices, but existing and new developers are encouraged to use Google Maps Android API v2.
MapFragment:不再需要繼承 MapActivity,改以 Fragment 方式嵌入,彈性大得多。代價是必須安裝 Google Play Services(實務上意味著需要帶 GMS 的原生 ROM),且需要較新的 SDK 版本。
WebView:把網頁版地圖包進來,理論上最不受限制,但效能與互動體驗都不如前兩者。
以下示範 MapFragment 的整合流程,官方文件在 https://developers.google.com/maps/documentation/android/start。
到 Google API Console 建立專案,開啟 API Access,先在 Services 中啟用「Google Maps Android API v2」,再到 API Access 填入你專案 keystore 的 SHA1 憑證與套件名稱,即可取得專屬的 API key。
開啟 SDK Manager,在 Extras 中安裝 Android Support Library 與 Google Play Services。相關檔案位於 <sdk>/extras/google/google_play_services/,把其中的 lib_project 匯入作為自己專案的 library 參考。
<permission
android:name="com.example.permission.MAPS_RECEIVE"
android:protectionLevel="signature"/>
<uses-permission android:name="com.example.permission.MAPS_RECEIVE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
<!-- My Location -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<!-- Maps API needs OpenGL ES 2.0 -->
<uses-feature
android:glEsVersion="0x00020000"
android:required="true"/>
記得把 com.example 換成自己專案的套件名稱。接著在 application 節點內加上 API key:
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="你的 API Key"/>
<fragment xmlns:android="https://schemas.android.com/apk/res/android"
android:id="@+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.MapFragment"/>
Activity 端就單純多了,直接繼承 Activity 即可,不必再綁 MapActivity。
Debug 簽章看不到地圖。這是初學者最常回報的問題。API key 是綁定 keystore 憑證的,debug 用的預設 keystore 和正式簽名不同,因此一定要用正式簽名打包安裝,地圖才會正常顯示。
另外補充兩點實務經驗:定位權限屬於危險權限,在 Android 6.0 以上必須在執行期動態向使用者申請,光在 manifest 宣告是不夠的;Google Maps API v2 也只能用於有安裝 Google Play Services 的裝置,若目標客群包含中國大陸或無 GMS 的機型,需要另外評估替代方案。
Android Spinner 進度條:按鈕觸發與顯示控制
Spinner 的顯示時機當使用者等待網路請求、檔案讀取或資料處理時,不確定型進度條可以作為視覺回饋。Android 中通常使用 ProgressBar 搭配 large
Android WebView 網頁載入與回退處理
WebView 的基本用法 WebView 可在應用程式中顯示網頁。使用 new WebView 建立物件,再以 loadUrl 載入線上網址或 assets 中的本機檔
Android MediaPlayer 深入應用:從播放狀態機到自訂快轉秒數
Android 提供了許多方法來控制音訊/視訊檔案與串流的播放,而其中最根本的一個入口,就是名為 MediaPlayer 的類別。它讓你能以純 Java 的方式存取系統內
Android 開機自啟實作:攔截 BOOT_COMPLETED 廣播
我們有時會希望 App 能在 Android 裝置開機完成後自動啟動,就像 Windows 裡那些常駐程式一樣——例如某些背景 Service 需要定期從網路上更新內容。