高德地图线路规划+导航

准备工作在以前一篇博客中写过了: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

以及高德官网

posted @ 2016-06-01 19:48  下雨天rain  阅读(4658)  评论(0编辑  收藏  举报