編輯:關於 Android 程式設計
本文示範如何在 Android 中整合高德地圖的導航能力,涵蓋 3D 導航檢視、路徑規劃、模擬/GPS 導航切換,以及搭配訊飛語音引擎的即時播報。以下程式碼為完整可運作的 Activity 與語音控制器。
AmapNaviActivity 同時實作了 AMapNaviListener、AMapNaviViewListener 與 AMapLocationListener,負責檢視、導航與定位三件事:
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.widget.FrameLayout;
import android.widget.FrameLayout.LayoutParams;
import android.widget.Toast;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationClientOption.AMapLocationMode;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.navi.AMapNavi;
import com.amap.api.navi.AMapNaviListener;
import com.amap.api.navi.AMapNaviView;
import com.amap.api.navi.AMapNaviViewListener;
import com.amap.api.navi.AMapNaviViewOptions;
import com.amap.api.navi.enums.NaviType;
import com.amap.api.navi.model.AMapLaneInfo;
import com.amap.api.navi.model.AMapNaviCross;
import com.amap.api.navi.model.AMapNaviInfo;
import com.amap.api.navi.model.AMapNaviLocation;
import com.amap.api.navi.model.AMapNaviTrafficFacilityInfo;
import com.amap.api.navi.model.AimLessModeCongestionInfo;
import com.amap.api.navi.model.AimLessModeStat;
import com.amap.api.navi.model.NaviInfo;
import com.amap.api.navi.model.NaviLatLng;
import com.autonavi.tbt.TrafficFacilityInfo;
/**
* 高德地圖導航 Activity
*/
@SuppressWarnings("deprecation")
public class AmapNaviActivity extends Activity implements AMapNaviListener, AMapNaviViewListener, AMapLocationListener {
private static final String TAG = AmapNaviActivity.class.getName();
/** 3D 導航地圖物件 */
private AMapNaviView mAMapNaviView;
/** 導航物件 */
private AMapNavi mAMapNavi;
/** 語音物件 */
private TTSController mTtsManager;
/** 起點座標 */
private final List startList = new ArrayList();
/** 終點座標 */
private final List endList = new ArrayList();
/** 途經點座標 */
private List mWayPointList = new ArrayList();
/** 定位參數 */
private AMapLocationClientOption mLocationOption = null;
/** 定位客戶端 */
private AMapLocationClient mlocationClient = null;
/** 導航方式 */
private NaviWay naviWay;
/** 導航參數 */
private JSONArray naviData;
/** 執行緒 handle */
private Handler handler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mAMapNaviView = new AMapNaviView(this);
FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
mAMapNaviView.setLayoutParams(layoutParams);
setContentView(mAMapNaviView);
naviWay = (NaviWay) getIntent().getSerializableExtra(AMapNaviPlugin.NAVI_WAY);
try {
naviData = new JSONArray(getIntent().getStringExtra(AMapNaviPlugin.NAVI_DATA));
} catch (Exception e) {
Log.e(TAG, e.getMessage());
finish();
}
initNaviData();
try {
// 起點座標為空則取得裝置當前座標作為起點
JSONObject startPos = naviData.getJSONObject(0);
startList.add(new NaviLatLng(startPos.optDouble("latitude"), startPos.optDouble("longitude")));
initNavi();
} catch (Exception e) {
// 使用定位取得當前座標
Log.i(TAG, "起點座標為空,取得裝置定位座標作為起點。");
initLocation();
}
mAMapNaviView.onCreate(savedInstanceState);
setAmapNaviViewOptions();
mAMapNaviView.setAMapNaviViewListener(this);
}
// ... 其餘方法與回呼實作省略,詳見下方說明
}
關鍵流程說明:initNaviData() 依導航方式解析終點與最多三個途經點;initNavi() 初始化語音引擎並設定模擬導航速度;initLocation() 在缺少起點座標時以高精度模式定位,並透過 onLocationChanged() 回呼取得座標後啟動導航。
路徑規劃在 onInitNaviSuccess() 中進行,透過 strategyConvert() 設定躲避擁堵、避免收費、高速優先等策略(注意「不走高速」與「高速優先」、「高速優先」與「避免收費」不能同時為 true),再依步行或駕車呼叫 calculateWalkRoute() 或 calculateDriveRoute()。路徑規劃成功後,onCalculateRouteSuccess() 會依參數選擇 NaviType.EMULATOR(模擬)或 NaviType.GPS(真實)啟動導航。
別忘了生命週期管理:在 onPause() 中呼叫 mAMapNaviView.onPause() 並停止語音;在 onDestroy() 中依序釋放導航檢視、stopNavi()、destroy() 語音與定位客戶端,避免資源洩漏。
TTSController 使用訊飛語音合成引擎,實作 SynthesizerListener 與 AMapNaviListener,把導航事件即時轉為語音播報:
import android.content.Context;
import android.os.Bundle;
import com.iflytek.cloud.speech.SpeechError;
import com.iflytek.cloud.speech.SpeechListener;
import com.iflytek.cloud.speech.SpeechSynthesizer;
import com.iflytek.cloud.speech.SpeechUser;
import com.iflytek.cloud.speech.SynthesizerListener;
/**
* 導航語音播報(訊飛)
*/
@SuppressWarnings("deprecation")
public class TTSController implements SynthesizerListener, AMapNaviListener {
public static TTSController ttsManager;
boolean isfinish = true;
private Context mContext;
private SpeechSynthesizer mSpeechSynthesizer;
TTSController(Context context) {
mContext = context;
}
public static TTSController getInstance(Context context) {
if (ttsManager == null) {
ttsManager = new TTSController(context);
}
return ttsManager;
}
public void init() {
// 登入語音服務(appid 需替換為你自己的)
SpeechUser.getUser().login(mContext, null, null, "appid=" + "輸入您訊飛的appid", listener);
mSpeechSynthesizer = SpeechSynthesizer.createSynthesizer(mContext);
initSpeechSynthesizer();
}
public void playText(String playText) {
if (!isfinish) { return; }
if (null == mSpeechSynthesizer) {
mSpeechSynthesizer = SpeechSynthesizer.createSynthesizer(mContext);
initSpeechSynthesizer();
}
mSpeechSynthesizer.startSpeaking(playText, this);
}
public void stopSpeaking() {
if (mSpeechSynthesizer != null) {
mSpeechSynthesizer.stopSpeaking();
}
}
public void startSpeaking() {
isfinish = true;
}
private void initSpeechSynthesizer() {
// 可設定發音人、語速、音量、語調等參數
}
// 導航事件轉語音播報
@Override public void onArriveDestination() { this.playText("到達目的地"); }
@Override public void onCalculateRouteFailure(int arg0) { this.playText("路徑計算失敗,請檢查網路或輸入參數"); }
@Override public void onCalculateRouteSuccess() { this.playText("路徑計算就緒"); }
@Override public void onEndEmulatorNavi() { this.playText("導航結束"); }
@Override public void onGetNavigationText(int arg0, String arg1) { this.playText(arg1); }
@Override public void onReCalculateRouteForTrafficJam() { this.playText("前方路線擁堵,路線重新規劃"); }
@Override public void onReCalculateRouteForYaw() { this.playText("您已偏航"); }
// ... 其餘回呼為空實作
}
整合時要注意幾個重點:出發前需在專案加入高德 SDK 與訊飛 SDK 的依賴,並在 Manifest 中申請定位、網路、儲存等權限;TTSController 以單例形式管理語音合成,透過 playText() 依導航行為(到達、偏航、擁堵、路徑就緒等)觸發播報;而 isfinish 旗標可避免語音尚未播完時又插入新語音造成打斷。
透過 AMapNaviView 承載導航畫面、AMapNavi 負責路徑與導航邏輯、TTSController 負責語音回饋,三者搭配即可打造一個具備即時語音提示的完整導航體驗。
Android軟鍵盤處理詳解:焦點控制與windowSoftInputMode實踐
問題一:控制項焦點與軟鍵盤自動彈出 在Android開發中,若EditText處理不當,頁面一打開就可能自動取得焦點,導致軟鍵盤立即彈出,影響使用者體驗。 一種常見的解法
Android ListView 與 ExpandableListView 實現多選、單選、全選與批量輸入
下圖為列表多選與批量輸入的示意。 ListView 多選與全選 在 Adapter 中可用 Map 或 SparseArray 記錄每一列的勾選狀態。getView 時
Android網絡檢測實戰:判斷聯網狀態並引導用戶去設置
專案裡經常需要確認設備當前是否處於聯網狀態。本文記錄如何檢測網絡連接,並在離線時彈出提示框,引導使用者直接跳到系統網絡設置頁。 效果預覽 (1)聯網情況下: (2)未聯
跨平台行動 App 開發框架 iMAG 入門指南
iMAG 是一個相當輕巧的跨平台行動開發框架,寫一次即可同時支援 Android 與 iOS,只要有 Web 開發基礎就能快速上手。市面上跨平台方案不少,iMAG 的關鍵