高德地圖線路規划+導航


准備工作在以前一篇博客中寫過了:http://www.cnblogs.com/rainday1/p/5305469.html

但是官網下載的最新jar包不需要單獨導入定位包,而且有些類過時了,所以這里面的方法可能與上一篇有點不一樣

工程結構:

0.准備類

TTSController.java

package util;

import android.content.Context;
import android.os.Bundle;

import com.amap.api.navi.AMapNaviListener;
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.autonavi.tbt.TrafficFacilityInfo;
import com.example.bmap.R;
import com.iflytek.cloud.speech.SpeechConstant;
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;

/**
 * 璇煶鎾姤緇勪歡
 */
public class TTSController implements SynthesizerListener, AMapNaviListener {

    public static TTSController ttsManager;
    boolean isfinish = true;
    private Context mContext;
    // 鍚堟垚瀵硅薄.
    private SpeechSynthesizer mSpeechSynthesizer;
    /**
     * 鐢ㄦ埛鐧誨綍鍥炶皟鐩戝惉鍣�.
     */
    private SpeechListener listener = new SpeechListener() {

        @Override
        public void onData(byte[] arg0) {
        }

        @Override
        public void onCompleted(SpeechError error) {
            if (error != null) {

            }
        }

        @Override
        public void onEvent(int arg0, Bundle arg1) {
        }
    };

    TTSController(Context context) {
        mContext = context;
    }

    public static TTSController getInstance(Context context) {
        if (ttsManager == null) {
            ttsManager = new TTSController(context);
        }
        return ttsManager;
    }

    public void init() {
        SpeechUser.getUser().login(mContext, null, null,
                "appid=" + mContext.getString(R.string.app_id), listener);
        // 鍒濆鍖栧悎鎴愬璞�.
        mSpeechSynthesizer = SpeechSynthesizer.createSynthesizer(mContext);
        initSpeechSynthesizer();
    }

    /**
     * 浣跨敤SpeechSynthesizer鍚堟垚璇煶錛屼笉寮瑰嚭鍚堟垚Dialog.
     *
     * @param
     */
    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() {
        // 璁劇疆鍙戦煶浜�
        mSpeechSynthesizer.setParameter(SpeechConstant.VOICE_NAME,
                mContext.getString(R.string.preference_default_tts_role));
        // 璁劇疆璇��
        mSpeechSynthesizer.setParameter(SpeechConstant.SPEED,
                "" + mContext.getString(R.string.preference_key_tts_speed));
        // 璁劇疆闊抽噺
        mSpeechSynthesizer.setParameter(SpeechConstant.VOLUME,
                "" + mContext.getString(R.string.preference_key_tts_volume));
        // 璁劇疆璇皟
        mSpeechSynthesizer.setParameter(SpeechConstant.PITCH,
                "" + mContext.getString(R.string.preference_key_tts_pitch));

    }

    @Override
    public void onBufferProgress(int arg0, int arg1, int arg2, String arg3) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onCompleted(SpeechError arg0) {
        // TODO Auto-generated method stub
        isfinish = true;
    }

    @Override
    public void onSpeakBegin() {
        // TODO Auto-generated method stub
        isfinish = false;

    }

    @Override
    public void onSpeakPaused() {
        // TODO Auto-generated method stub

    }

    @Override
    public void onSpeakProgress(int arg0, int arg1, int arg2) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onSpeakResumed() {
        // TODO Auto-generated method stub

    }

    public void destroy() {
        if (mSpeechSynthesizer != null) {
            mSpeechSynthesizer.stopSpeaking();
        }
    }

    @Override
    public void onArriveDestination() {
        // TODO Auto-generated method stub
        this.playText("鍒拌揪鐩殑鍦�");
    }

    @Override
    public void onArrivedWayPoint(int arg0) {
        // TODO Auto-generated method stub
    }

    @Override
    public void onCalculateRouteFailure(int arg0) {
        this.playText("璺緞璁$畻澶辮觸錛岃媯�鏌ョ綉緇滄垨杈撳叆鍙傛暟");
    }

    @Override
    public void onCalculateRouteSuccess() {
        String calculateResult = "璺緞璁$畻灝辯華";

        this.playText(calculateResult);
    }

    @Override
    public void onEndEmulatorNavi() {
        this.playText("瀵艱埅緇撴潫");

    }

    @Override
    public void onGetNavigationText(int arg0, String arg1) {
        // TODO Auto-generated method stub
        this.playText(arg1);
    }

    @Override
    public void onInitNaviFailure() {
        // TODO Auto-generated method stub

    }

    @Override
    public void onInitNaviSuccess() {
        // TODO Auto-generated method stub

    }

    @Override
    public void onLocationChange(AMapNaviLocation arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onReCalculateRouteForTrafficJam() {
        // TODO Auto-generated method stub
        this.playText("鍓嶆柟璺嚎鎷ュ牭錛岃礬綰塊噸鏂拌鍒�");
    }

    @Override
    public void onReCalculateRouteForYaw() {

        this.playText("鎮ㄥ凡鍋忚埅");
    }

    @Override
    public void onStartNavi(int arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onTrafficStatusUpdate() {
        // TODO Auto-generated method stub

    }

    @Override
    public void onGpsOpenStatus(boolean arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onNaviInfoUpdated(AMapNaviInfo arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onNaviInfoUpdate(NaviInfo arg0) {

        // TODO Auto-generated method stub

    }

    @Override
    public void OnUpdateTrafficFacility(TrafficFacilityInfo trafficFacilityInfo) {

    }

    @Override
    public void OnUpdateTrafficFacility(AMapNaviTrafficFacilityInfo aMapNaviTrafficFacilityInfo) {

    }

    @Override
    public void showCross(AMapNaviCross aMapNaviCross) {

    }

    @Override
    public void hideCross() {

    }

    @Override
    public void showLaneInfo(AMapLaneInfo[] aMapLaneInfos, byte[] bytes, byte[] bytes1) {

    }

    @Override
    public void hideLaneInfo() {

    }

    @Override
    public void onCalculateMultipleRoutesSuccess(int[] ints) {

    }

    @Override
    public void notifyParallelRoad(int i) {

    }

    @Override
    public void OnUpdateTrafficFacility(AMapNaviTrafficFacilityInfo[] aMapNaviTrafficFacilityInfos) {

    }

    @Override
    public void updateAimlessModeStatistics(AimLessModeStat aimLessModeStat) {

    }


    @Override
    public void updateAimlessModeCongestionInfo(AimLessModeCongestionInfo aimLessModeCongestionInfo) {

    }
}
View Code

Utils.java

package util;

public class Utils {
    public static final String DAY_NIGHT_MODE = "daynightmode";
    public static final String DEVIATION = "deviationrecalculation";
    public static final String JAM = "jamrecalculation";
    public static final String TRAFFIC = "trafficbroadcast";
    public static final String CAMERA = "camerabroadcast";
    public static final String SCREEN = "screenon";
    public static final String THEME = "theme";
    public static final String ISEMULATOR = "isemulator";


    public static final String ACTIVITYINDEX = "activityindex";

    public static final int SIMPLEHUDNAVIE = 0;
    public static final int EMULATORNAVI = 1;
    public static final int SIMPLEGPSNAVI = 2;
    public static final int SIMPLEROUTENAVI = 3;


    public static final boolean DAY_MODE = false;
    public static final boolean NIGHT_MODE = true;
    public static final boolean YES_MODE = true;
    public static final boolean NO_MODE = false;
    public static final boolean OPEN_MODE = true;
    public static final boolean CLOSE_MODE = false;

}
View Code

border.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >  
  
    <solid android:color="@color/grey" />  
  
    <stroke  
        android:width="0.1dp"  
        android:color="@color/black" />  
  
    <padding  
        android:bottom="1dp"  
        android:left="0.5dp"  
        android:right="0.5dp"  
        android:top="0dp" />  
</shape>  
View Code

whiteborder.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >  
  
    <solid android:color="@color/white" />  
  
    <stroke  
        android:width="0.1dp"  
        android:color="@color/black" />  
  
    <padding  
        android:bottom="1dp"  
        android:left="0.5dp"  
        android:right="0.5dp"  
        android:top="0dp" />  
</shape>  
View Code

whitedownborder.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >  
  
    <solid android:color="@color/white" />  
  
    <stroke  
        android:width="0.1dp"  
        android:color="@color/black" />  
  
   
</shape>  
View Code

線路規划:

1.分配權限

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.bmap"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="14"
        android:targetSdkVersion="18" />
     <!-- //地圖包、搜索包需要的基礎權限 -->
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <!-- 定位包、導航包需要的額外權限(注:基礎權限也需要) -->
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
    <uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />

    
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        
       
        
        <meta-data
            android:name="com.amap.api.v2.apikey"
            android:value="d278999928c69d384aabcc4493c40e36"/>
        <!-- 定位需要的服務 -->
        <service android:name="com.amap.api.location.APSService" >
        </service>
  
        
        <activity
            android:name="com.example.bmap.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity 
            android:name="com.example.bmap.NaviCustomActivity"></activity>
        <activity 
            android:name="com.example.bmap.NaviRouteActivity"></activity>
        <activity 
            android:name="com.example.bmap.NaviSettingActivity"
            android:theme="@android:style/Theme.DeviceDefault.Dialog.NoActionBar"></activity>
    </application>

</manifest>
View Code

2.主頁面,顯示地圖+定位+路徑規划

activity.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/grey"
    android:orientation="vertical" >
    
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <Button
            android:id="@+id/btn_bus"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:onClick="doClick"
            android:text="bus" />

        <Button
            android:id="@+id/btn_car"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:onClick="doClick"
            android:text="car" />

        <Button
            android:id="@+id/btn_walk"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:onClick="doClick"
            android:text="walk" />
<!--         <Button
            android:id="@+id/btn_beginNavigation"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:onClick="doClick"
            android:text="Navigation" /> -->
    </LinearLayout>
        
<!--     <com.amap.api.maps.MapView
        android:id="@+id/map"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    </com.amap.api.maps.MapView> -->
             
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:background="@drawable/border" >

        <com.amap.api.maps.MapView
            android:id="@+id/map"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </LinearLayout>

    <TextView
        android:id="@+id/map_err"
        android:layout_width="match_parent"
        android:visibility="gone"
        android:layout_height="310dp" />
    
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:paddingBottom="@dimen/margin_bottom"
            android:paddingLeft="@dimen/margin_left"
            android:paddingTop="@dimen/margin_top"
            android:text="@string/routeinfo_1"
            android:textColor="@color/black"
            android:textSize="@dimen/route_text_size" />

        <TextView
            android:id="@+id/navi_route_distance_1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:paddingBottom="@dimen/margin_bottom"
            android:paddingLeft="@dimen/margin_left"
            android:paddingTop="@dimen/margin_top"
            android:text="@string/routeinfo_default"
            android:textColor="@color/red"
            android:textSize="@dimen/route_text_size" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:paddingBottom="@dimen/margin_bottom"
            android:paddingTop="@dimen/margin_top"
            android:text="@string/routeinfo_2"
            android:textColor="@color/black"
            android:textSize="@dimen/route_text_size" />

        <TextView
            android:id="@+id/navi_route_time_1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:paddingBottom="@dimen/margin_bottom"
            android:paddingLeft="@dimen/margin_left"
            android:paddingTop="@dimen/margin_top"
            android:text="@string/routeinfo_default"
            android:textColor="@color/red"
            android:textSize="@dimen/route_text_size" />

        <TextView
            android:id="@+id/navi_route_cost_before"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:paddingBottom="@dimen/margin_bottom"
            android:paddingTop="@dimen/margin_top"
            android:text="@string/routeinfo_3"
            android:textColor="@color/black"
            android:textSize="@dimen/route_text_size" />

        <TextView
            android:id="@+id/navi_route_cost_1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:paddingBottom="@dimen/margin_bottom"
            android:paddingLeft="@dimen/margin_left"
            android:paddingTop="@dimen/margin_top"
            android:text="@string/routeinfo_default"
            android:textColor="@color/red"
            android:singleLine="true"
            android:textSize="@dimen/route_text_size" />

        <TextView
            android:id="@+id/navi_route_cost_after"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:paddingBottom="@dimen/margin_bottom"
            android:paddingTop="@dimen/margin_top"
            android:text="@string/routeinfo_4"
            android:textColor="@color/black"
            android:textSize="@dimen/route_text_size" />
    </LinearLayout>

   <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <Button
            android:id="@+id/btn_beginNavigation"
            android:layout_width="match_parent"
            android:layout_height="@dimen/naviroute_navi_height"
            android:layout_alignParentRight="true"
            android:onClick="doClick"
            android:text="@string/start_navi_navi" />


    </RelativeLayout>

</LinearLayout>
View Code

MainActivity.java

package com.example.bmap;

import java.util.ArrayList;
import java.util.List;

import util.TTSController;
import android.app.ActionBar;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.location.Location;
import android.media.AudioManager;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
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.AMapLocationListener;
import com.amap.api.location.AMapLocationClientOption.AMapLocationMode;
import com.amap.api.maps.AMap;
import com.amap.api.maps.AMap.OnMapClickListener;
import com.amap.api.maps.AMap.OnMapLoadedListener;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.LocationSource.OnLocationChangedListener;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.overlay.BusRouteOverlay;
import com.amap.api.maps.overlay.DrivingRouteOverlay;
import com.amap.api.maps.overlay.WalkRouteOverlay;
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.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.AMapNaviPath;
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.amap.api.navi.view.RouteOverLay;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.route.BusPath;
import com.amap.api.services.route.BusRouteResult;
import com.amap.api.services.route.DrivePath;
import com.amap.api.services.route.DriveRouteResult;
import com.amap.api.services.route.RouteSearch;
import com.amap.api.services.route.WalkPath;
import com.amap.api.services.route.WalkRouteResult;
import com.amap.api.services.route.RouteSearch.OnRouteSearchListener;
import com.autonavi.tbt.TrafficFacilityInfo;

public class MainActivity extends Activity implements LocationSource,
        AMapLocationListener, OnRouteSearchListener,OnMapLoadedListener,AMapNaviViewListener {
    private MapView mMapView = null;
    private AMap aMap;
    // private LocationManagerProxy mLocationManagerProxy;
    private AMapLocationClient locationClient = null;
    private AMapLocationClientOption locationOption = null;
    private OnLocationChangedListener mListener;
    TextView mLocationErrText;

    RouteSearch.FromAndTo fromAndTo;// 起始點和終點的經緯度
    private RouteSearch mRouteSearch;

    private TextView mRouteDistanceView;// 距離顯示控件
    private TextView mRouteTimeView;// 時間顯示控件
    private TextView mRouteCostView;// 花費顯示控件    
    private AMapNaviView mAmapAMapNaviView;
    private AMapNavi mAmapNavi;
    private RouteOverLay routeOverLay;
    private boolean mIsMapLoaded = false;
    private AMapNaviListener mAmapNaviListener;
    private ProgressDialog mProgressDialog;// 路徑規划過程顯示狀態
    private int mNaviMethod;
    private boolean mIsGetGPS = false;// 記錄GPS定位是否成功
    private NaviLatLng mStartPoint = new NaviLatLng();
    private List<NaviLatLng> mStartPoints = new ArrayList<NaviLatLng>();
    private Marker mGPSMarker;
 // 記錄地圖點擊事件相應情況,根據選擇不同,地圖響應不同
    private int mMapClickMode = MAP_CLICK_NO;
    private static final int MAP_CLICK_NO = 0;// 地圖不接受點擊事件
    private static final int MAP_CLICK_START = 1;// 地圖點擊設置起點
    private static final int MAP_CLICK_WAY = 2;// 地圖點擊設置途經點
       private static final int MAP_CLICK_END = 3;// 地圖點擊設置終點

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mLocationErrText = (TextView) findViewById(R.id.map_err);

        // 獲取地圖控件引用
        mMapView = (MapView) findViewById(R.id.map);
        // 在activity執行onCreate時執行mMapView.onCreate(savedInstanceState),實現地圖生命周期管理
        mMapView.onCreate(savedInstanceState);

        if (aMap == null) {// 初始化aMap
            aMap = mMapView.getMap();
        }
        aMap.setLocationSource(this);// 設置定位監聽
        aMap.getUiSettings().setMyLocationButtonEnabled(true);// 設置默認定位按鈕是否顯示
        aMap.setMyLocationEnabled(true);// 設置為true表示顯示定位層並可觸發定位,false表示隱藏定位層並不可觸發定位,默認是false
        // 設置定位的類型為定位模式,參見類AMap。定位(AMap.LOCATION_TYPE_LOCATE)、跟隨(AMap.LOCATION_TYPE_MAP_FOLLOW)根據面向方向旋轉(AMap.LOCATION_TYPE_MAP_ROTATE)
        aMap.setMyLocationType(AMap.LOCATION_TYPE_LOCATE);

        aMap.getUiSettings().setCompassEnabled(true);// 指南針
        aMap.getUiSettings().setZoomGesturesEnabled(true);// 通過手勢縮放地圖
        aMap.getUiSettings().setScrollGesturesEnabled(true);// 手勢平移(滑動)地圖
        aMap.getUiSettings().setRotateGesturesEnabled(true);// 手勢旋轉地圖
        aMap.getUiSettings().setTiltGesturesEnabled(true);// 手勢傾斜地圖

        aMap.moveCamera(CameraUpdateFactory.zoomTo(14));
        // //修改地圖的中心點位置
        // CameraPosition cp = aMap.getCameraPosition();
        // CameraPosition cpNew = CameraPosition.fromLatLngZoom(new
        // LatLng(31.22, 121.48), cp.zoom);
        // CameraUpdate cu = CameraUpdateFactory.newCameraPosition(cpNew);
        // aMap.moveCamera(cu);

        mRouteSearch = new RouteSearch(this);// 初始化routeSearch 對象
        mRouteSearch.setRouteSearchListener(this);// 設置數據回調監聽器
        LatLonPoint start = new LatLonPoint(30.577082, 114.33167);// 起點114.331662,30.577063物電學院//坐標拾取的坐標反了
                                                                    // 為安師大新校區的經緯度31.286389,
                                                                    // 118.378039
        LatLonPoint end = new LatLonPoint(30.57836, 114.334886);// 終點114.334886,30.57836圖書館
                                                                // 為皖南醫學院的經緯度31.288702,
                                                                // 118.360532
        fromAndTo = new RouteSearch.FromAndTo(start, end);// 實例化FromAndTo,字面意思,哪到哪
        setVolumeControlStream(AudioManager.STREAM_MUSIC);// 設置聲音控制
        // 設置語音模塊播報
        mAmapNavi = AMapNavi.getInstance(this);// 初始化導航引擎
        mRouteDistanceView = (TextView) findViewById(R.id.navi_route_distance_1);
        mRouteTimeView = (TextView) findViewById(R.id.navi_route_time_1);
        mRouteCostView = (TextView) findViewById(R.id.navi_route_cost_1);        
         
        routeOverLay = new RouteOverLay(aMap, null);
        TTSController ttsManager = TTSController.getInstance(this);// 初始化語音模塊
        ttsManager.init();
        AMapNavi.getInstance(this).setAMapNaviListener(ttsManager);// 設置語音模塊播報
        mGPSMarker = aMap.addMarker(new MarkerOptions()
                .icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory
                        .decodeResource(getResources(),
                                R.drawable.location_marker))));
        

        /* 顯示App icon左側的back鍵 */
        ActionBar actionBar = getActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
    }

    public void doClick(View view) {

        switch (view.getId()) {
        case R.id.btn_bus:
            RouteSearch.BusRouteQuery busRouteQuery = new RouteSearch.BusRouteQuery(
                    fromAndTo, RouteSearch.BusDefault, "武漢", 0);// 第一個參數表示路徑規划的起點和終點,第二個參數表示公交查詢模式,第三個參數表示公交查詢城市區號,第四個參數表示是否計算夜班車,0表示不計算
            mRouteSearch.calculateBusRouteAsyn(busRouteQuery);
            break;
        case R.id.btn_car:
            RouteSearch.DriveRouteQuery driveRouteQuery = new RouteSearch.DriveRouteQuery(
                    fromAndTo, RouteSearch.DrivingDefault, null, null, "");
            mRouteSearch.calculateDriveRouteAsyn(driveRouteQuery);
            
            aMap.clear();// 清除地圖上的標注之類
            //駕車點
            List<NaviLatLng> mEndPoints = new ArrayList<NaviLatLng>();
            //114.332926,30.576153
            List<NaviLatLng> mWayPoints = new ArrayList<NaviLatLng>();
            mWayPoints.add(new NaviLatLng((mStartPoint.getLatitude()+30.576153)/2, (mStartPoint.getLongitude()+114.332926)/2));
            mEndPoints.add(new NaviLatLng(30.57836, 114.334886));
            mAmapNavi.calculateDriveRoute(mStartPoints, mEndPoints,mWayPoints, AMapNavi.DrivingDefault);
            
//            initNavi();
            break;
        case R.id.btn_walk:
            RouteSearch.WalkRouteQuery walkRouteQuery = new RouteSearch.WalkRouteQuery(
                    fromAndTo, RouteSearch.WalkDefault);
            mRouteSearch.calculateWalkRouteAsyn(walkRouteQuery);
            
            aMap.clear();// 清除地圖上的標注之類
            NaviLatLng start = new NaviLatLng(mStartPoint.getLatitude(),mStartPoint.getLongitude());
            NaviLatLng end = new NaviLatLng(30.57836, 114.334886);// 114.339726,30.573219
            mAmapNavi.calculateWalkRoute(start, end);
            
//            initNavi();

            break;
        case R.id.btn_beginNavigation://導航
            Intent standIntent = new Intent(MainActivity.this,NaviCustomActivity.class);
            standIntent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
//            initNavi();
            startActivity(standIntent);            
            break;
        }
    }

    // 頂部返回鍵
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case android.R.id.home:
            finish();
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }
    
    /**
     * 初始化路線描述信息和加載線路
     */
    private void initNavi() {
        
        // NaviLatLng start = new NaviLatLng(30.577082, 114.33167);//114.33246,30.57548嘉會園
//        NaviLatLng start = new NaviLatLng(mStartPoint.getLatitude(),mStartPoint.getLongitude());
//        NaviLatLng end = new NaviLatLng(30.57836, 114.334886);// 114.339726,30.573219
//        mAmapNavi.calculateWalkRoute(start, end);
//        //駕車點
//        List<NaviLatLng> mEndPoints = new ArrayList<NaviLatLng>();
//        //114.332926,30.576153
//        List<NaviLatLng> mWayPoints = new ArrayList<NaviLatLng>();
//        mWayPoints.add(new NaviLatLng((mStartPoint.getLatitude()+30.576153)/2, (mStartPoint.getLongitude()+114.332926)/2));
//        mEndPoints.add(new NaviLatLng(30.57836, 114.334886));
//        mAmapNavi.calculateDriveRoute(mStartPoints, mEndPoints,mWayPoints, AMapNavi.DrivingDefault);
        
        mAmapNavi.startGPS();
        TTSController.getInstance(this).startSpeaking();
        
        mAmapNavi = AMapNavi.getInstance(this);
        AMapNaviPath naviPath = mAmapNavi.getNaviPath();
        if (naviPath == null) {
            return;
        }
        // 獲取路徑規划線路,顯示到地圖上
        routeOverLay.setRouteInfo(naviPath);
        routeOverLay.addToMap();
//        if (mIsMapLoaded) {
//            routeOverLay.zoomToSpan();
//        }
        routeOverLay.zoomToSpan();
        
        double length = ((int) (naviPath.getAllLength() / (double) 1000 * 10))
                / (double) 10;
        // 不足分鍾 按分鍾計
        int time = (naviPath.getAllTime() + 59) / 60;
        int cost = naviPath.getTollCost();
        mRouteDistanceView.setText(String.valueOf(length));
        mRouteTimeView.setText(String.valueOf(time));
        mRouteCostView.setText(String.valueOf(cost));
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 在activity執行onDestroy時執行mMapView.onDestroy(),實現地圖生命周期管理
        mMapView.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 在activity執行onResume時執行mMapView.onResume (),實現地圖生命周期管理
        mMapView.onResume();
//        initNavi();
        // 以下兩句邏輯是為了保證進入首頁開啟定位和加入導航回調
        AMapNavi.getInstance(this).setAMapNaviListener(getAMapNaviListener());
//        NaviLatLng start = new NaviLatLng(30.577082, 114.33167);//114.33246,30.57548嘉會園
////        NaviLatLng start = new NaviLatLng(location.getLatitude(), location.getLongitude());
//        NaviLatLng end = new NaviLatLng(30.57836, 114.334886);//114.339726,30.573219
//        mAmapNavi.calculateWalkRoute(start,end);
//        mAmapNavi.startGPS();
//        TTSController.getInstance(this).startSpeaking();
    }

    @Override
    protected void onPause() {
        super.onPause();
        deactivate();
        // 在activity執行onPause時執行mMapView.onPause (),實現地圖生命周期管理
        mMapView.onPause();
        // 下邊邏輯是移除監聽
        AMapNavi.getInstance(this).removeAMapNaviListener(getAMapNaviListener());
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        // 在activity執行onSaveInstanceState時執行mMapView.onSaveInstanceState
        // (outState),實現地圖生命周期管理
        mMapView.onSaveInstanceState(outState);
    }

    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
        // TODO Auto-generated method stub
        if (mListener != null && amapLocation != null) {
            if (amapLocation != null && amapLocation.getErrorCode() == 0) {
                mLocationErrText.setVisibility(View.GONE);
                mStartPoint=new NaviLatLng(amapLocation.getLatitude(), amapLocation.getLongitude());
                mListener.onLocationChanged(amapLocation);// 顯示系統小藍點
                
                mGPSMarker.setPosition(new LatLng(mStartPoint.getLatitude(),
                        mStartPoint.getLongitude()));
                mStartPoints.clear();
                mStartPoints.add(mStartPoint);
                                
                
            } else {
                String errText = "定位失敗," + amapLocation.getErrorCode();// + ": "
                                                                        // +
                                                                        // amapLocation.getErrorInfo()
                Log.e("AmapErr", errText);
                mLocationErrText.setVisibility(View.VISIBLE);
                mLocationErrText.setText(errText);
            }
        }
    }

    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {
        // TODO Auto-generated method stub
        mListener = onLocationChangedListener;
        if (locationClient == null) {
            locationClient = new AMapLocationClient(
                    this.getApplicationContext());
            locationOption = new AMapLocationClientOption();
            locationClient.setLocationListener(this);// 設置定位監聽
//            locationOption.setOnceLocation(true);// 設置為單次定位
            locationOption.setLocationMode(AMapLocationMode.Hight_Accuracy); // 設置定位模式為低功耗模式
            locationClient.setLocationOption(locationOption); // 設置定位參數
            locationClient.startLocation(); // 啟動定位
        }

    }

    @Override
    public void deactivate() {
        // TODO Auto-generated method stub
        mListener = null;
        if (locationClient != null) {
            locationClient.stopLocation();
            locationClient.onDestroy();
        }
        locationClient = null;
        locationOption = null;
    }

    @Override
    public void onBusRouteSearched(BusRouteResult busRouteResult, int arg1) {
        // TODO Auto-generated method stub
        BusPath busPath = busRouteResult.getPaths().get(0);// 取其中一個路線
        aMap.clear();
        BusRouteOverlay routeOverlay = new BusRouteOverlay(this, aMap, busPath,
                busRouteResult.getStartPos(), busRouteResult.getTargetPos());
        routeOverlay.removeFromMap();
        routeOverlay.addToMap();
        routeOverlay.zoomToSpan();
    }

    @Override
    public void onDriveRouteSearched(DriveRouteResult driveRouteResult,
            int rCode) {
        // TODO Auto-generated method stub
        if (rCode == 1000) {
            //注釋的代碼是路線規划用的,不能顯示在導航界面,如果不注釋在路線規划的時候會有兩天線路
//            DrivePath drivePath = driveRouteResult.getPaths().get(0);
//            aMap.clear();
//            DrivingRouteOverlay routeOverlay = new DrivingRouteOverlay(this,
//                    aMap, drivePath, driveRouteResult.getStartPos(),
//                    driveRouteResult.getTargetPos());
//            routeOverlay.removeFromMap();
//            routeOverlay.addToMap();
//            routeOverlay.zoomToSpan();
            
            initNavi();
        }
    }

    @Override
    public void onWalkRouteSearched(WalkRouteResult walkRouteResult, int rCode) {
        // TODO Auto-generated method stub
        if (rCode == 1000) {
            if (walkRouteResult != null && walkRouteResult.getPaths() != null
                    && walkRouteResult.getPaths().size() > 0) {
                //注釋的代碼是路線規划用的,不能顯示在導航界面,如果不注釋在路線規划的時候會有兩天線路
//                WalkPath walkPath = walkRouteResult.getPaths().get(0);// 取其中一個路線
//                aMap.clear();// 清除地圖上的標注之類
//                WalkRouteOverlay routeOverlay = new WalkRouteOverlay(this,
//                        aMap, walkPath, walkRouteResult.getStartPos(),
//                        walkRouteResult.getTargetPos());
//                routeOverlay.removeFromMap();
//                routeOverlay.addToMap();
//                routeOverlay.zoomToSpan();                
                
                initNavi();
            } else {
                showToast("對不起,沒有搜索到相關數據!");
            }
        } else if (rCode == 1102) {
            showToast("搜索失敗,請檢查網絡連接!");
        } else if (rCode == 1002) {
            showToast("key驗證無效!");
        } else {
            showToast("未知錯誤,請稍后重試!錯誤碼為" + rCode);
        }
        
//        mIsGetGPS=false;
        
    }

    /**
     * toast封裝
     * 
     * @param str
     */
    private void showToast(String str) {
        Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onMapLoaded() {
        // TODO Auto-generated method stub
        mIsMapLoaded = true;
        if (routeOverLay != null) {
            routeOverLay.zoomToSpan();

        }
    }
    
    /**
     * 導航回調函數
     * 
     * @return
     */
    private AMapNaviListener getAMapNaviListener() {
        if (mAmapNaviListener == null) {

            mAmapNaviListener = new AMapNaviListener() {
          
                @Override
                public void onTrafficStatusUpdate() {
                    // TODO Auto-generated method stub

                }

                @Override
                public void onStartNavi(int arg0) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void onReCalculateRouteForYaw() {
                    // TODO Auto-generated method stub

                }

                @Override
                public void onReCalculateRouteForTrafficJam() {
                    // TODO Auto-generated method stub

                }

                @Override
                public void onLocationChange(AMapNaviLocation location) {
                    
                }

                @Override
                public void onInitNaviSuccess() {
                    // TODO Auto-generated method stub

                }

                @Override
                public void onInitNaviFailure() {
                    // TODO Auto-generated method stub

                }

                @Override
                public void onGetNavigationText(int arg0, String arg1) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void onEndEmulatorNavi() {
                    // TODO Auto-generated method stub

                }

                @Override
                public void onCalculateRouteSuccess() {
                    dissmissProgressDialog();
                    switch (mNaviMethod) {
                    //路徑規划
                    case R.id.btn_beginNavigation:
                        Intent standIntent = new Intent(MainActivity.this,
                                NaviRouteActivity.class);
                        // standIntent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                        startActivity(standIntent);
                        break;
//                    //模擬導航
//                    case NAVI_METHOD:
//                        Intent standIntent = new Intent(MainActivity.this,
//                                NaviCustomActivity.class);
//                        standIntent
//                                .addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
//                        startActivity(standIntent);
//                        break;
                    }
                }

                @Override
                public void onCalculateRouteFailure(int arg0) {
                    dissmissProgressDialog();
                    showToast("路徑規划出錯");
                }

                @Override
                public void onArrivedWayPoint(int arg0) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void onArriveDestination() {
                    // TODO Auto-generated method stub

                }

                @Override
                public void onGpsOpenStatus(boolean arg0) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void onNaviInfoUpdated(AMapNaviInfo arg0) {
                    // TODO Auto-generated method stub
                    
                }

                @Override
                public void onNaviInfoUpdate(NaviInfo arg0) {
                      
                    // TODO Auto-generated method stub  
                    
                }

                @Override
                @Deprecated
                public void OnUpdateTrafficFacility(
                        AMapNaviTrafficFacilityInfo arg0) {
                    // TODO Auto-generated method stub
                    
                }

                @Override
                @Deprecated
                public void OnUpdateTrafficFacility(TrafficFacilityInfo arg0) {
                    // TODO Auto-generated method stub
                    
                }

                @Override
                public void OnUpdateTrafficFacility(
                        AMapNaviTrafficFacilityInfo[] arg0) {
                    // TODO Auto-generated method stub
                    
                }

                @Override
                public void hideCross() {
                    // TODO Auto-generated method stub
                    
                }

                @Override
                public void hideLaneInfo() {
                    // TODO Auto-generated method stub
                    
                }

                @Override
                public void notifyParallelRoad(int arg0) {
                    // TODO Auto-generated method stub
                    
                }

                @Override
                public void onCalculateMultipleRoutesSuccess(int[] arg0) {
                    // TODO Auto-generated method stub
                    
                }

                @Override
                public void showCross(AMapNaviCross arg0) {
                    // TODO Auto-generated method stub
                    
                }

                @Override
                public void showLaneInfo(AMapLaneInfo[] arg0, byte[] arg1,
                        byte[] arg2) {
                    // TODO Auto-generated method stub
                    
                }

                @Override
                public void updateAimlessModeCongestionInfo(
                        AimLessModeCongestionInfo arg0) {
                    // TODO Auto-generated method stub
                    
                }

                @Override
                public void updateAimlessModeStatistics(AimLessModeStat arg0) {
                    // TODO Auto-generated method stub
                    
                }
            };
        }
        return mAmapNaviListener;
    }
    
    /**
     * 隱藏進度框
     */
    private void dissmissProgressDialog() {
        if (mProgressDialog != null) {
            mProgressDialog.dismiss();
        }
    }

    @Override
    public void onLockMap(boolean arg0) {
        // TODO Auto-generated method stub
        
    }

    @Override
    public boolean onNaviBackClick() {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public void onNaviCancel() {
        // TODO Auto-generated method stub
        
    }

    @Override
    public void onNaviMapMode(int arg0) {
        // TODO Auto-generated method stub
        
    }

    @Override
    public void onNaviSetting() {
        // TODO Auto-generated method stub
        
    }

    @Override
    public void onNaviTurnClick() {
        // TODO Auto-generated method stub
        
    }

    @Override
    public void onNaviViewLoaded() {
        // TODO Auto-generated method stub
        
    }

    @Override
    public void onNextRoadClick() {
        // TODO Auto-generated method stub
        
    }

    @Override
    public void onScanViewButtonClick() {
        // TODO Auto-generated method stub
        
    }


}
View Code

3.這個類其實沒用到,參照別人的把這個也加進來了,MainActivity跳轉dao此頁面的實際在我的工程中沒有工作

activity_route.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/grey"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/border" >

        <ImageView
            android:id="@+id/route_back_view"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginBottom="@dimen/margin_bottom"
            android:layout_marginTop="@dimen/margin_top"
            android:src="@drawable/back_top" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginBottom="@dimen/margin_bottom"
            android:layout_marginTop="@dimen/margin_top"
            android:layout_weight="1"
            android:gravity="center_horizontal"
            android:text="@string/routeshow"
            android:textColor="@color/black"
            android:textSize="@dimen/titletext_size" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:background="@drawable/border" >

        <com.amap.api.maps.MapView
            android:id="@+id/routemap"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:paddingBottom="@dimen/margin_bottom"
            android:paddingLeft="@dimen/margin_left"
            android:paddingTop="@dimen/margin_top"
            android:text="@string/routeinfo_1"
            android:textColor="@color/black"
            android:textSize="@dimen/route_text_size" />

        <TextView
            android:id="@+id/navi_route_distance"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:paddingBottom="@dimen/margin_bottom"
            android:paddingLeft="@dimen/margin_left"
            android:paddingTop="@dimen/margin_top"
            android:text="@string/routeinfo_default"
            android:textColor="@color/red"
            android:textSize="@dimen/route_text_size" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:paddingBottom="@dimen/margin_bottom"
            android:paddingTop="@dimen/margin_top"
            android:text="@string/routeinfo_2"
            android:textColor="@color/black"
            android:textSize="@dimen/route_text_size" />

        <TextView
            android:id="@+id/navi_route_time"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:paddingBottom="@dimen/margin_bottom"
            android:paddingLeft="@dimen/margin_left"
            android:paddingTop="@dimen/margin_top"
            android:text="@string/routeinfo_default"
            android:textColor="@color/red"
            android:textSize="@dimen/route_text_size" />

        <TextView
            android:id="@+id/navi_route_cost_before"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:paddingBottom="@dimen/margin_bottom"
            android:paddingTop="@dimen/margin_top"
            android:text="@string/routeinfo_3"
            android:textColor="@color/black"
            android:textSize="@dimen/route_text_size" />

        <TextView
            android:id="@+id/navi_route_cost"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:paddingBottom="@dimen/margin_bottom"
            android:paddingLeft="@dimen/margin_left"
            android:paddingTop="@dimen/margin_top"
            android:text="@string/routeinfo_default"
            android:textColor="@color/red"
            android:singleLine="true"
            android:textSize="@dimen/route_text_size" />

        <TextView
            android:id="@+id/navi_route_cost_after"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:paddingBottom="@dimen/margin_bottom"
            android:paddingTop="@dimen/margin_top"
            android:text="@string/routeinfo_4"
            android:textColor="@color/black"
            android:textSize="@dimen/route_text_size" />
    </LinearLayout>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <Button
            android:id="@+id/routestartnavi"
            android:layout_width="wrap_content"
            android:layout_height="@dimen/naviroute_navi_height"
            android:layout_alignParentRight="true"
            android:text="@string/start_navi_navi" />

        <AutoCompleteTextView
            android:id="@+id/navi_theme_text"
            android:layout_width="wrap_content"
            android:layout_height="@dimen/naviroute_navi_height"
            android:layout_alignParentLeft="true"
            android:layout_toLeftOf="@id/routestartnavi"
            android:focusable="false"
            android:hint="@string/theme_blue" >
        </AutoCompleteTextView>

        <ImageView
            android:id="@+id/navi_theme_image"
            android:layout_width="wrap_content"
            android:layout_height="@dimen/naviroute_navi_height"
            android:layout_alignBottom="@+id/navi_theme_text"
            android:layout_alignRight="@+id/navi_theme_text"
            android:layout_alignTop="@id/navi_theme_text"
            android:layout_marginRight="@dimen/margin_right"
            android:src="@drawable/downarrow" />
    </RelativeLayout>

</LinearLayout>
View Code

NaviRouteActivity.java

package com.example.bmap;

import android.app.Activity;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.text.InputType;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.amap.api.maps.AMap;
import com.amap.api.maps.MapView;
import com.amap.api.maps.AMap.OnMapLoadedListener;
import com.amap.api.navi.AMapNavi;
import com.amap.api.navi.AMapNaviViewOptions;
import com.amap.api.navi.model.AMapNaviPath;
import com.amap.api.navi.view.RouteOverLay;

/**
 * 路徑規划結果展示界面
 */
public class NaviRouteActivity extends Activity implements OnClickListener,
        OnMapLoadedListener {

    // View
    private Button mStartNaviButton;// 實時導航按鈕
    private MapView mMapView;// 地圖控件
    private AutoCompleteTextView mThemeText;// 選擇導航界面的風格
    private ImageView mThemeImage;// 選擇按鈕
    private ImageView mRouteBackView;// 返回按鈕
    private TextView mRouteDistanceView;// 距離顯示控件
    private TextView mRouteTimeView;// 時間顯示控件
    private TextView mRouteCostView;// 花費顯示控件
    // 地圖導航資源
    private AMap mAmap;
    private AMapNavi mAmapNavi;
    private RouteOverLay mRouteOverLay;
    // 主題數組
    private String mTheme[];

    private boolean mIsMapLoaded = false;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_route);
        initResources();
        initView(savedInstanceState);
        //MainApplication.getInstance().addActivity(this);
    }

    // -----------------------初始化----------------------------------

    /**
     * 初始化資源
     */
    private void initResources() {
        Resources res = getResources();
        mTheme = new String[] { res.getString(R.string.theme_blue),
                res.getString(R.string.theme_pink),
                res.getString(R.string.theme_white) };
    }

    /**
     * 初始化控件
     */
    private void initView(Bundle savedInstanceState) {
        mStartNaviButton = (Button) findViewById(R.id.routestartnavi);

        mRouteBackView = (ImageView) findViewById(R.id.route_back_view);

        mThemeText = (AutoCompleteTextView) findViewById(R.id.navi_theme_text);
        mThemeText.setInputType(InputType.TYPE_NULL);
//        ArrayAdapter<String> themeAdapter = new ArrayAdapter<String>(this,
//                R.layout.strategy_inputs, mTheme);
//        mThemeText.setAdapter(themeAdapter);

        mThemeText.setDropDownBackgroundResource(R.drawable.whitedownborder);

        mThemeImage = (ImageView) findViewById(R.id.navi_theme_image);
        mRouteDistanceView = (TextView) findViewById(R.id.navi_route_distance);
        mRouteTimeView = (TextView) findViewById(R.id.navi_route_time);
        mRouteCostView = (TextView) findViewById(R.id.navi_route_cost);
        mMapView = (MapView) findViewById(R.id.routemap);
        mMapView.onCreate(savedInstanceState);
        mAmap = mMapView.getMap();
        mAmap.setOnMapLoadedListener(this);
        mThemeImage.setOnClickListener(this);
        mThemeText.setOnClickListener(this);
        mStartNaviButton.setOnClickListener(this);
        mRouteBackView.setOnClickListener(this);
        mRouteOverLay = new RouteOverLay(mAmap, null);
    }

    /**
     * 初始化路線描述信息和加載線路
     */
    private void initNavi() {
        
        mAmapNavi = AMapNavi.getInstance(this);
        AMapNaviPath naviPath = mAmapNavi.getNaviPath();
        if (naviPath == null) {
            return;
        }
        // 獲取路徑規划線路,顯示到地圖上
        mRouteOverLay.setRouteInfo(naviPath);
        mRouteOverLay.addToMap();
        if (mIsMapLoaded) {
            mRouteOverLay.zoomToSpan();
        }

        double length = ((int) (naviPath.getAllLength() / (double) 1000 * 10))
                / (double) 10;
        // 不足分鍾 按分鍾計
        int time = (naviPath.getAllTime() + 59) / 60;
        int cost = naviPath.getTollCost();
        mRouteDistanceView.setText(String.valueOf(length));
        mRouteTimeView.setText(String.valueOf(time));
        mRouteCostView.setText(String.valueOf(cost));
    }

    /**
     * 獲取導航界面主題樣式
     * 
     * @param themeColor
     * @return
     */
    private int getThemeStyle(String themeColor) {
        int theme = AMapNaviViewOptions.BLUE_COLOR_TOPIC;
        if (mTheme[0].equals(themeColor)) {
            theme = AMapNaviViewOptions.BLUE_COLOR_TOPIC;
        } else if (mTheme[1].equals(themeColor)) {
            theme = AMapNaviViewOptions.PINK_COLOR_TOPIC;
        } else if (mTheme[2].equals(themeColor)) {
            theme = AMapNaviViewOptions.WHITE_COLOR_TOPIC;
        }
        return theme;
    }

    // ------------------------------事件處理-----------------------------
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        // 實時導航操作
        case R.id.routestartnavi:
            Bundle bundle = new Bundle();
            bundle.putInt("theme", getThemeStyle(mThemeText.getText().toString()));
            Intent routeIntent = new Intent(NaviRouteActivity.this,
                    NaviCustomActivity.class);
            routeIntent.putExtras(bundle);
            startActivity(routeIntent);
            break;
        // 返回操作
        case R.id.route_back_view:
            Intent startIntent = new Intent(NaviRouteActivity.this,
                    MainActivity.class);
            startIntent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
            startActivity(startIntent);
            //MainApplication.getInstance().deleteActivity(this);
            finish();
            break;
        // 主題選擇
        case R.id.navi_theme_image:
        case R.id.navi_theme_text:
            mThemeText.showDropDown();
            break;
        }

    }

    /**
     * 
     * 返回鍵監聽
     * */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent intent = new Intent(NaviRouteActivity.this,
                    MainActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
            startActivity(intent);
            //MainApplication.getInstance().deleteActivity(this);
            finish();

        }
        return super.onKeyDown(keyCode, event);
    }

    // ------------------------------生命周期必須重寫方法---------------------------
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mMapView.onSaveInstanceState(outState);
    }

    @Override
    public void onResume() {
        super.onResume();
        mMapView.onResume();
        initNavi();
    }

    @Override
    public void onPause() {
        super.onPause();
        mMapView.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mMapView.onDestroy();
    }

    @Override
    public void onMapLoaded() {
        mIsMapLoaded = true;
        if (mRouteOverLay != null) {
            mRouteOverLay.zoomToSpan();

        }
    }

}
View Code

4.導航頁面

fragment_navistander.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    
    <com.amap.api.navi.AMapNaviView
    android:id="@+id/navimap"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>
    
</LinearLayout>
View Code

NaviCustomActivity.java

package com.example.bmap;

import util.TTSController;
import util.Utils;

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.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.autonavi.tbt.TrafficFacilityInfo;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;

public class NaviCustomActivity extends Activity implements
        AMapNaviViewListener {
    private AMapNaviView mAmapAMapNaviView;
    // 導航可以設置的參數
    private boolean mDayNightFlag = Utils.DAY_MODE;// 默認為白天模式
    private boolean mDeviationFlag = Utils.YES_MODE;// 默認進行偏航重算
    private boolean mJamFlag = Utils.YES_MODE;// 默認進行擁堵重算
    private boolean mTrafficFlag = Utils.OPEN_MODE;// 默認進行交通播報
    private boolean mCameraFlag = Utils.OPEN_MODE;// 默認進行攝像頭播報
    private boolean mScreenFlag = Utils.YES_MODE;// 默認是屏幕常亮
    // 導航界面風格
    private int mThemeStle;
    // 導航監聽
    private AMapNaviListener mAmapNaviListener;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_navistander);
        //語音播報開始
        TTSController.getInstance(this).startSpeaking();
        // 實時導航方式進行導航,模擬導航時把此條語句注釋掉
        AMapNavi.getInstance(this).startNavi(AMapNavi.GPSNaviMode);
        
        init(savedInstanceState);
    }

    /**
     * 初始化
     * 
     * @param savedInstanceState
     */
    private void init(Bundle savedInstanceState) {
        mAmapAMapNaviView = (AMapNaviView) findViewById(R.id.navimap);
        mAmapAMapNaviView.onCreate(savedInstanceState);
        // 設置導航界面監聽
        mAmapAMapNaviView.setAMapNaviViewListener(this);
        setAmapNaviViewOptions();

//        // 設置模擬速度
//        AMapNavi.getInstance(this).setEmulatorNaviSpeed(100);
//        // 開啟模擬導航
//        AMapNavi.getInstance(this).startNavi(AMapNavi.EmulatorNaviMode);
    }    
    /**
     * 設置導航的參數
     */
    private void setAmapNaviViewOptions() {
        if (mAmapAMapNaviView == null) {
            return;
        }
        AMapNaviViewOptions viewOptions = new AMapNaviViewOptions();
        viewOptions.setSettingMenuEnabled(true);// 設置導航setting可用
        viewOptions.setNaviNight(mDayNightFlag);// 設置導航是否為黑夜模式
        viewOptions.setReCalculateRouteForYaw(mDeviationFlag);// 設置導偏航是否重算
        viewOptions.setReCalculateRouteForTrafficJam(mJamFlag);// 設置交通擁擠是否重算
        viewOptions.setTrafficInfoUpdateEnabled(mTrafficFlag);// 設置是否更新路況
        viewOptions.setCameraInfoUpdateEnabled(mCameraFlag);// 設置攝像頭播報
        viewOptions.setScreenAlwaysBright(mScreenFlag);// 設置屏幕常亮情況
        viewOptions.setNaviViewTopic(mThemeStle);// 設置導航界面主題樣式

        mAmapAMapNaviView.setViewOptions(viewOptions);

    }
    private AMapNaviListener getAMapNaviListener() {
        if (mAmapNaviListener == null) {

            mAmapNaviListener = new AMapNaviListener() {

                @Override
                public void onTrafficStatusUpdate() {
                    // TODO Auto-generated method stub

                }

                @Override
                public void onStartNavi(int arg0) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void onReCalculateRouteForYaw() {
                    // 可以在頻繁重算時進行設置,例如五次之后
                    int i = 0;
                    i++;
                    if (i >= 5) {
                        AMapNaviViewOptions viewOptions = new AMapNaviViewOptions();
                        viewOptions.setReCalculateRouteForYaw(false);
                        mAmapAMapNaviView.setViewOptions(viewOptions);
                    }
                }

                @Override
                public void onReCalculateRouteForTrafficJam() {

                }

                @Override
                public void onLocationChange(AMapNaviLocation location) {

                }

                @Override
                public void onInitNaviSuccess() {
                    // TODO Auto-generated method stub

                }

                @Override
                public void onInitNaviFailure() {
                    // TODO Auto-generated method stub

                }

                @Override
                public void onGetNavigationText(int arg0, String arg1) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void onEndEmulatorNavi() {
                    // TODO Auto-generated method stub

                }

                @Override
                public void onCalculateRouteSuccess() {

                }

                @Override
                public void onCalculateRouteFailure(int arg0) {

                }

                @Override
                public void onArrivedWayPoint(int arg0) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void onArriveDestination() {
                    // TODO Auto-generated method stub

                }

                @Override
                public void onGpsOpenStatus(boolean arg0) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void onNaviInfoUpdated(AMapNaviInfo arg0) {
                    // TODO Auto-generated method stub
                    
                }

                @Override
                public void onNaviInfoUpdate(NaviInfo arg0) {
                      
                    // TODO Auto-generated method stub  
                    
                }

                @Override
                @Deprecated
                public void OnUpdateTrafficFacility(
                        AMapNaviTrafficFacilityInfo arg0) {
                    // TODO Auto-generated method stub
                    
                }

                @Override
                @Deprecated
                public void OnUpdateTrafficFacility(TrafficFacilityInfo arg0) {
                    // TODO Auto-generated method stub
                    
                }

                @Override
                public void OnUpdateTrafficFacility(
                        AMapNaviTrafficFacilityInfo[] arg0) {
                    // TODO Auto-generated method stub
                    
                }

                @Override
                public void hideCross() {
                    // TODO Auto-generated method stub
                    
                }

                @Override
                public void hideLaneInfo() {
                    // TODO Auto-generated method stub
                    
                }

                @Override
                public void notifyParallelRoad(int arg0) {
                    // TODO Auto-generated method stub
                    
                }

                @Override
                public void onCalculateMultipleRoutesSuccess(int[] arg0) {
                    // TODO Auto-generated method stub
                    
                }

                @Override
                public void showCross(AMapNaviCross arg0) {
                    // TODO Auto-generated method stub
                    
                }

                @Override
                public void showLaneInfo(AMapLaneInfo[] arg0, byte[] arg1,
                        byte[] arg2) {
                    // TODO Auto-generated method stub
                    
                }

                @Override
                public void updateAimlessModeCongestionInfo(
                        AimLessModeCongestionInfo arg0) {
                    // TODO Auto-generated method stub
                    
                }

                @Override
                public void updateAimlessModeStatistics(AimLessModeStat arg0) {
                    // TODO Auto-generated method stub
                    
                }
            };
        }
        return mAmapNaviListener;
    }


    /**
     * 導航界面左下角返回按鈕回調
     * 
     */
    @Override
    public void onNaviCancel() {
        Intent intent = new Intent(NaviCustomActivity.this,
                MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
        startActivity(intent);
        finish();
    }

    /**
     * 導航界面右下角功能設置按鈕回調
     * 
     */
    @Override
    public void onNaviSetting() {
        Bundle bundle = new Bundle();
        bundle.putInt(Utils.THEME, mThemeStle);
        bundle.putBoolean(Utils.DAY_NIGHT_MODE, mDayNightFlag);
        bundle.putBoolean(Utils.DEVIATION, mDeviationFlag);
        bundle.putBoolean(Utils.JAM, mJamFlag);
        bundle.putBoolean(Utils.TRAFFIC, mTrafficFlag);
        bundle.putBoolean(Utils.CAMERA, mCameraFlag);
        bundle.putBoolean(Utils.SCREEN, mScreenFlag);
        Intent intent = new Intent(NaviCustomActivity.this,
                NaviSettingActivity.class);
        intent.putExtras(bundle);
        startActivity(intent);

    }

    @Override
    public void onNaviMapMode(int arg0) {
        // TODO Auto-generated method stub

    }

    private void processBundle(Bundle bundle) {

        if (bundle != null) {
            mDayNightFlag = bundle.getBoolean(Utils.DAY_NIGHT_MODE,
                    mDayNightFlag);
            mDeviationFlag = bundle.getBoolean(Utils.DEVIATION, mDeviationFlag);
            mJamFlag = bundle.getBoolean(Utils.JAM, mJamFlag);
            mTrafficFlag = bundle.getBoolean(Utils.TRAFFIC, mTrafficFlag);
            mCameraFlag = bundle.getBoolean(Utils.CAMERA, mCameraFlag);
            mScreenFlag = bundle.getBoolean(Utils.SCREEN, mScreenFlag);
            mThemeStle = bundle.getInt(Utils.THEME);

        }
    }
    @Override
    protected void onNewIntent(Intent intent) {
        // TODO Auto-generated method stub
        super.onNewIntent(intent);
        setIntent(intent);
    }
    /**
     * 返回鍵盤監聽
     * 
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent intent = new Intent(NaviCustomActivity.this,
                    MainActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
            startActivity(intent);
            finish();
        }
        return super.onKeyDown(keyCode, event);
    }

    // ------------------------------生命周期方法---------------------------
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mAmapAMapNaviView.onSaveInstanceState(outState);
    }

    @Override
    public void onResume() {
        super.onResume();
        Bundle bundle = getIntent().getExtras();
        processBundle(bundle);
        setAmapNaviViewOptions();
        AMapNavi.getInstance(this).setAMapNaviListener(getAMapNaviListener());
        mAmapAMapNaviView.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        mAmapAMapNaviView.onPause();
        AMapNavi.getInstance(this).removeAMapNaviListener(getAMapNaviListener());
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mAmapAMapNaviView.onDestroy();
         //頁面結束時,停止語音播報
        TTSController.getInstance(this).stopSpeaking();
    }

    @Override
    public void onLockMap(boolean arg0) {
        // TODO Auto-generated method stub
        
    }

    @Override
    public boolean onNaviBackClick() {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public void onNaviTurnClick() {
        // TODO Auto-generated method stub
        
    }

    @Override
    public void onNaviViewLoaded() {
        // TODO Auto-generated method stub
        
    }

    @Override
    public void onNextRoadClick() {
        // TODO Auto-generated method stub
        
    }

    @Override
    public void onScanViewButtonClick() {
        // TODO Auto-generated method stub
        
    }

}
View Code

 5.導航設置界面

activity_navisetting.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/grey"
    android:orientation="vertical" >

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="@dimen/setting_margin_bottom" >

        <ImageView
            android:id="@+id/setting_back_image"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/back_top" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_weight="1"
            android:gravity="center_horizontal"
            android:text="@string/setting"
            android:textColor="@color/black"
            android:textSize="@dimen/titletext_size" />
    </RelativeLayout>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="@dimen/setting_margin_bottom"
        android:layout_marginLeft="@dimen/navibar_margin_left"
        android:layout_marginRight="@dimen/navibar_margin_right"
        android:layout_marginTop="@dimen/setting_margin_top"
        android:layout_weight="1"
        android:gravity="center_vertical"
        android:background="@drawable/whiteborder" >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="@dimen/margin_left"
            android:layout_marginTop="10dp"
            android:gravity="center_vertical"
            android:text="@string/daynightmode"
            android:textColor="@color/black"
            android:textSize="@dimen/navisetting_subtext_size" />

        <RadioGroup
            android:id="@+id/day_night_group"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_marginRight="@dimen/margin_right"
            android:orientation="horizontal" >

            <RadioButton
                android:id="@+id/dayratio"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginRight="@dimen/margin_right"
                android:checked="true"
                android:text="@string/day"
                android:textColor="@color/black" />

            <RadioButton
                android:id="@+id/nightradio"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/night"
                android:textColor="@color/black" />
        </RadioGroup>
    </RelativeLayout>

    <RelativeLayout
         android:layout_weight="1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="@dimen/setting_margin_bottom"
        android:layout_marginLeft="@dimen/navibar_margin_left"
        android:layout_marginRight="@dimen/navibar_margin_right"
        android:layout_marginTop="@dimen/setting_margin_top"
          android:gravity="center_vertical"
        android:background="@drawable/whiteborder" >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="@dimen/margin_left"
            android:layout_marginTop="10dp"
            android:text="@string/deviationrecalculation"
            android:textColor="@color/black"
            android:textSize="@dimen/navisetting_subtext_size" />

        <RadioGroup
            android:id="@+id/deviation_group"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_marginRight="@dimen/margin_right"
            android:orientation="horizontal" >

            <RadioButton
                android:id="@+id/deviationyesradio"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginRight="@dimen/margin_right"
                android:checked="true"
                android:text="@string/yes"
                android:textColor="@color/black" />

            <RadioButton
                android:id="@+id/deviationnoradio"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/no"
                android:textColor="@color/black" />
        </RadioGroup>
    </RelativeLayout>

    <RelativeLayout
         android:layout_weight="1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
          android:gravity="center_vertical"
        android:layout_marginBottom="@dimen/setting_margin_bottom"
        android:layout_marginLeft="@dimen/navibar_margin_left"
        android:layout_marginRight="@dimen/navibar_margin_right"
        android:layout_marginTop="@dimen/setting_margin_top"
        android:background="@drawable/whiteborder" >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="@dimen/margin_left"
            android:layout_marginTop="10dp"
            android:text="@string/jamrecalculation"
            android:textColor="@color/black"
            android:textSize="@dimen/navisetting_subtext_size" />

        <RadioGroup
            android:id="@+id/jam_group"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_marginRight="@dimen/margin_right"
            android:orientation="horizontal" >

            <RadioButton
                android:id="@+id/jam_yes_radio"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginRight="@dimen/margin_right"
                android:checked="true"
                android:text="@string/yes"
                android:textColor="@color/black" />

            <RadioButton
                android:id="@+id/jam_no_radio"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/no"
                android:textColor="@color/black" />
        </RadioGroup>
    </RelativeLayout>

    <RelativeLayout
         android:layout_weight="1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
          android:gravity="center_vertical"
        android:layout_marginBottom="@dimen/setting_margin_bottom"
        android:layout_marginLeft="@dimen/navibar_margin_left"
        android:layout_marginRight="@dimen/navibar_margin_right"
        android:layout_marginTop="@dimen/setting_margin_top"
        android:background="@drawable/whiteborder" >

        <TextView
            android:id="@+id/textView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="@dimen/margin_left"
            android:layout_marginTop="10dp"
            android:text="@string/trafficbroadcast"
            android:textColor="@color/black"
            android:textSize="@dimen/navisetting_subtext_size" />

        <RadioGroup
            android:id="@+id/traffic_group"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
          android:layout_marginRight="@dimen/margin_right"
            android:orientation="horizontal" >

            <RadioButton
                android:id="@+id/trafficyesradio"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginRight="@dimen/margin_right"
                android:checked="true"
                android:text="@string/open"
                android:textColor="@color/black" />

            <RadioButton
                android:id="@+id/trafficnoradio"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/close"
                android:textColor="@color/black" />
        </RadioGroup>
    </RelativeLayout>

    <RelativeLayout
         android:layout_weight="1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
          android:gravity="center_vertical"
        android:layout_marginBottom="@dimen/setting_margin_bottom"
        android:layout_marginLeft="@dimen/navibar_margin_left"
        android:layout_marginRight="@dimen/navibar_margin_right"
        android:layout_marginTop="@dimen/setting_margin_top"
        android:background="@drawable/whiteborder" >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="@dimen/margin_left"
            android:layout_marginTop="10dp"
            android:text="@string/camerabroadcast"
            android:textColor="@color/black"
            android:textSize="@dimen/navisetting_subtext_size" />

        <RadioGroup
            android:id="@+id/camera_group"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_marginRight="@dimen/margin_right"
            android:orientation="horizontal" >

            <RadioButton
                android:id="@+id/camerayesradio"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginRight="@dimen/margin_right"
                android:checked="true"
                android:text="@string/open"
                android:textColor="@color/black" />

            <RadioButton
                android:id="@+id/cameranoradio"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/close"
                android:textColor="@color/black" />
        </RadioGroup>
    </RelativeLayout>

    <RelativeLayout
         android:layout_weight="1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
          android:gravity="center_vertical"
        android:layout_marginBottom="@dimen/setting_margin_bottom"
        android:layout_marginLeft="@dimen/navibar_margin_left"
        android:layout_marginRight="@dimen/navibar_margin_right"
        android:layout_marginTop="@dimen/setting_margin_top"
        android:background="@drawable/whiteborder" >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="@dimen/margin_left"
            android:layout_marginTop="10dp"
            android:text="@string/screenon"
            android:textColor="@color/black"
            android:textSize="@dimen/navisetting_subtext_size" />

        <RadioGroup
            android:id="@+id/screen_group"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
        android:layout_marginRight="@dimen/margin_right"
            android:orientation="horizontal" >

            <RadioButton
                android:id="@+id/screenonradio"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginRight="@dimen/margin_right"
                android:checked="true"
                android:text="@string/yes"
                android:textColor="@color/black" />

            <RadioButton
                android:id="@+id/screenoffradio"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/no"
                android:textColor="@color/black" />
        </RadioGroup>
    </RelativeLayout>

</LinearLayout>
View Code

NaviSettingActivity.java

package com.example.bmap;

import util.Utils;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;

import com.amap.api.navi.AMapNaviViewOptions;


/**
 * 導航設置界面
 *
 */
public class NaviSettingActivity extends Activity implements OnClickListener,
        OnCheckedChangeListener {
    // ----------------View

    private ImageView mBackView;//返回按鈕
    private RadioGroup mDayNightGroup;//黑夜模式白天模式
    private RadioGroup mDeviationGroup;//偏航重算
    private RadioGroup mJamGroup;//擁堵重算
    private RadioGroup mTrafficGroup;//交通播報
    private RadioGroup mCameraGroup;//攝像頭播報
    private RadioGroup mScreenGroup;//屏幕常亮

    private boolean mDayNightFlag = Utils.DAY_MODE;
    private boolean mDeviationFlag = Utils.YES_MODE;
    private boolean mJamFlag = Utils.YES_MODE;
    private boolean mTrafficFlag = Utils.OPEN_MODE;
    private boolean mCameraFlag = Utils.OPEN_MODE;
    private boolean mScreenFlag = Utils.YES_MODE;
    private int mThemeStyle;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_navisetting);
        Bundle bundle=getIntent().getExtras();
        processBundle(bundle);
        initView();
        initListener();
    }


    /**
     * 初始化控件
     */
    private void initView() {
        mBackView = (ImageView) findViewById(R.id.setting_back_image);
        mDayNightGroup = (RadioGroup) findViewById(R.id.day_night_group);
        mDeviationGroup = (RadioGroup) findViewById(R.id.deviation_group);
        mJamGroup = (RadioGroup) findViewById(R.id.jam_group);
        mTrafficGroup = (RadioGroup) findViewById(R.id.traffic_group);
        mCameraGroup = (RadioGroup) findViewById(R.id.camera_group);
        mScreenGroup = (RadioGroup) findViewById(R.id.screen_group);

    }

    /**
     * 初始化監聽事件
     */
    private void initListener() {
        mBackView.setOnClickListener(this);
        mDayNightGroup.setOnCheckedChangeListener(this);
        mDeviationGroup.setOnCheckedChangeListener(this);
        mJamGroup.setOnCheckedChangeListener(this);
        mTrafficGroup.setOnCheckedChangeListener(this);
        mCameraGroup.setOnCheckedChangeListener(this);
        mScreenGroup.setOnCheckedChangeListener(this);

    }

    /**
     * 根據導航界面傳過來的數據設置當前界面的顯示狀態
     */
    private void setViewContent() {
        if (mDayNightGroup == null) {
            return;
        }
        if (mDayNightFlag) {
            mDayNightGroup.check(R.id.nightradio);
        } else {
            mDayNightGroup.check(R.id.dayratio);
        }
        if (mDeviationFlag) {
            mDeviationGroup.check(R.id.deviationyesradio);
        } else {
            mDeviationGroup.check(R.id.deviationnoradio);
        }

        if (mJamFlag) {
            mJamGroup.check(R.id.jam_yes_radio);
        } else {
            mJamGroup.check(R.id.jam_no_radio);
        }

        if (mTrafficFlag) {
            mTrafficGroup.check(R.id.trafficyesradio);
        } else {
            mTrafficGroup.check(R.id.trafficnoradio);
        }

        if (mCameraFlag) {
            mCameraGroup.check(R.id.camerayesradio);
        } else {
            mCameraGroup.check(R.id.cameranoradio);
        }

        if (mScreenFlag) {
            mScreenGroup.check(R.id.screenonradio);
        } else {
            mScreenGroup.check(R.id.screenoffradio);
        }
    }

    /**
     * 處理具體的bundle
     * @param bundle
     */
    private void processBundle(Bundle bundle) {
        if (bundle != null) {
            mThemeStyle = bundle.getInt(Utils.THEME,
                    AMapNaviViewOptions.DEFAULT_COLOR_TOPIC);
            mDayNightFlag = bundle.getBoolean(Utils.DAY_NIGHT_MODE);
            mDeviationFlag = bundle.getBoolean(Utils.DEVIATION);
            mJamFlag = bundle.getBoolean(Utils.JAM);
            mTrafficFlag = bundle.getBoolean(Utils.TRAFFIC);
            mCameraFlag = bundle.getBoolean(Utils.CAMERA);
            mScreenFlag = bundle.getBoolean(Utils.SCREEN);

        }
    }

    /**
     * 根據當前界面的設置設置,構建bundle
     * @return
     */
    private Bundle getBundle() {
        Bundle bundle = new Bundle();
        bundle.putBoolean(Utils.DAY_NIGHT_MODE, mDayNightFlag);
        bundle.putBoolean(Utils.DEVIATION, mDeviationFlag);
        bundle.putBoolean(Utils.JAM, mJamFlag);
        bundle.putBoolean(Utils.TRAFFIC, mTrafficFlag);
        bundle.putBoolean(Utils.CAMERA, mCameraFlag);
        bundle.putBoolean(Utils.SCREEN, mScreenFlag);
        bundle.putInt(Utils.THEME, mThemeStyle);
        return bundle;
    }

    // 事件處理方法
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.setting_back_image:

            Intent intent = new Intent(NaviSettingActivity.this,
                    NaviCustomActivity.class);
            intent.putExtras(getBundle());
            intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
            startActivity(intent);
            finish();
            break;
        }

    }

    
/**
 * 返回鍵監聽
 * */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent intent = new Intent(NaviSettingActivity.this,
                    NaviCustomActivity.class);
            intent.putExtras(getBundle());
            intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
            startActivity(intent);
            finish();

        }
        return super.onKeyDown(keyCode, event);
    }

    // ------------------------------生命周期重寫方法---------------------------

    @Override
    public void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        setViewContent();
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (checkedId) {
        // 晝夜模式
        case R.id.dayratio:
            mDayNightFlag = Utils.DAY_MODE;
            break;
        case R.id.nightradio:
            mDayNightFlag = Utils.NIGHT_MODE;
            break;
        // 偏航重算
        case R.id.deviationyesradio:
            mDeviationFlag = Utils.YES_MODE;
            break;
        case R.id.deviationnoradio:
            mDeviationFlag = Utils.NO_MODE;
            break;
        // 擁堵重算
        case R.id.jam_yes_radio:
            mJamFlag = Utils.YES_MODE;
            break;
        case R.id.jam_no_radio:
            mJamFlag = Utils.NO_MODE;
            break;
        // 交通播報
        case R.id.trafficyesradio:
            mTrafficFlag = Utils.OPEN_MODE;
            break;
        case R.id.trafficnoradio:
            mTrafficFlag = Utils.CLOSE_MODE;
            break;
        // 攝像頭播報
        case R.id.camerayesradio:
            mCameraFlag = Utils.OPEN_MODE;
            break;
        case R.id.cameranoradio:
            mCameraFlag = Utils.CLOSE_MODE;
            break;
            // 屏幕常亮
        case R.id.screenonradio:
            mScreenFlag = Utils.YES_MODE;
            break;
        case R.id.screenoffradio:
            mScreenFlag = Utils.NO_MODE;
            break;
        }

    }
}
View Code

 由於模擬器無法實現導航,我這里就沒有錄屏,直接截幾個界面圖

 主要參考博客:http://www.cnblogs.com/ouyangduoduo/p/4623680.html

以及高德官網


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM